如何在角度2中动态更改css类名 [英] How to change the css class name dynamically in angular 2

查看:22
本文介绍了如何在角度2中动态更改css类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个CSS类名如下

.icon_heart{颜色:#bdbdbd;}.icon_heart_red{颜色:#a6b7d4;;}

我的 HTML 有一个心形图标

<div class="icon_heart" *ngIf="showheartIcon">

这里我有两个 div 标签,心形图标最初是灰色,点击后我会将其更改为蓝色.

这是我的 ts 文件代码:

 showheartIcon=true;showheartIconRed =假;setWishlistTrue(id){this.showheartIconRed = true;this.showheartIcon = false;}setWishlistFalse(id){this.showheartIconRed = false;this.showheartIcon = true;}

我有两个不同颜色的图标.

问题

是否可以更改图标的类别而不是两个心形图标?

我在 JavaScript 中看到我们可以更改它w3schools 简单的方法将类应用于 div 标签,但我是 TypeScript 的新手.如何更改班级?

解决方案

<div [ngClass]="showheartIconRead ? 'icon_heart_red' : 'icon_heart'">

I have two CSS class name as follows

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color:#a6b7d4;;
}

My HTML has a heart icon

<div class="icon_heart" *ngIf="showheartIcon">
    <ion-icon name="heart" (click)="setWishlistTrue(category.product_id);" class="heart"></ion-icon>
</div>
<div class="icon_heart_red" *ngIf="showheartIconRed">
    <ion-icon name="heart" (click)="setWishlistFalse(category.product_id);" class="heart"></ion-icon>
</div>

Here I have two div tags, the heart icon is of gray color initially and on clicking that I will change it to blue color.

Here is my ts file code:

  showheartIcon=true;
  showheartIconRed =false;

  setWishlistTrue(id){
    this.showheartIconRed = true;
    this.showheartIcon = false;
  }

  setWishlistFalse(id){
    this.showheartIconRed = false;
    this.showheartIcon = true;
  }

I have two icons of different color.

Question

Instead of having two heart icons is it possible to change the class of the icon?

I have seen in JavaScript we can change it w3schools simple way to apply class to the div tag, but I am new to TypeScript. How can I change the class?

解决方案

<div 
    [class.icon_heart]="!showheartIconRead"
    [class.icon_heart_red]="showheartIconRead">

or

<div [ngClass]="showheartIconRead ? 'icon_heart_red' : 'icon_heart'">

这篇关于如何在角度2中动态更改css类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆