Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the css class name dynamically in angular 2

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?

like image 482
Mohan Gopi Avatar asked Sep 15 '16 09:09

Mohan Gopi


1 Answers

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

<div class="{{showheartIconRead ? 'icon_heart_red' : 'icon_heart' }}">
like image 188
Sanju Avatar answered Sep 21 '22 04:09

Sanju