Html 如何在angular 2中动态更改css类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39507346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:49:00  来源:igfitidea点击:

How to change the css class name dynamically in angular 2

htmlcssangularionic2

提问by Mohan Gopi

I have two CSS class name as follows

我有两个 CSS 类名如下

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color:#a6b7d4;;
}

My HTML has a heart icon

我的 HTML 有一个心形图标

<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 colorinitially and on clicking that I will change it to blue color.

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

Here is my ts file code:

这是我的 ts 文件代码:

  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 w3schoolssimple way to apply class to the div tag, but I am new to TypeScript. How can I change the class?

我已经在 J​​avaScript 中看到我们可以改变它w3schools将类应用于 div 标签的简单方法,但我是 TypeScript 的新手。我怎样才能改变班级?

回答by Günter Z?chbauer

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

or

或者

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

回答by Sanju

In addition to the above answer. this is also possible.

除了上面的答案。这也是可能的。

<div class="{{showheartIconRead ? 'icon_heart_red' : 'icon_heart' }}">