How to change css class name dynamically in angular 2

I have two CSS class names 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 gray , and when I click it will change to blue .

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 colors.

Question

Instead of two heart icons, can you change the icon class?

I saw in JavaScript, we can change it w3schools an easy way to apply a class to a div tag, but I'm new to TypeScript. How to change a class?

+5
source share
2 answers
 <div [class.icon_heart]="!showheartIconRead" [class.icon_heart_red]="showheartIconRead"> 

or

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

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

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

All Articles