Search code examples
htmlcssangularionic2

How can I dynamically change CSS class names in an Angular application?


I have two CSS class names as follows.

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color: #a6b7d4;;
}

My HTML contains 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>

There are two div elements. The heart icon has a grey colour until the user clicks it, then it should change to blue.

The following block of code is from my TypeScript file; two icons with different colours.

  showheartIcon = true;
  showheartIconRed = false;

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

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

Is it possible to replace the class of the icon, instead of having two of them?

I have seen in JavaScript that I can add a class to any HTML element.

How can I achieve that in Angular?


Solution

  • You can change CSS class names using the following options.

    Option 1

    <div 
        [class.icon_heart]="!showheartIconRed"
        [class.icon_heart_red]="showheartIconRed">This is an example.</div>
    

    Option 2

    <div [ngClass]="showheartIconRed ? 'icon_heart_red' : 'icon_heart'">This is another example.</div>