简体   繁体   English

如何在角度2中动态更改css类名称

[英]How to change the css class name dynamically in angular 2

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 color initially 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 w3schools simple way to apply class to the div tag, but I am new to TypeScript. 我在JavaScript中看到我们可以改变它w3schools将类应用于div标签的简单方法,但我是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'">

In addition to the above answer. 除了上面的答案。 this is also possible. 这也是可能的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM