如何在 angular 2 中动态更改 css class 名称

How to change the css class name dynamically in angular 2

我有两个CSSclass名字如下

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color:#a6b7d4;;
}

我的 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>

这里我有两个div标签,心形图标最初是灰色,点击它我会把它变成蓝色.

这是我的 ts 文件代码:

  showheartIcon=true;
  showheartIconRed =false;

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

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

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

问题

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

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

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

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

除了上面的回答。这也是可以的。

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