Angular - Change Font Awesome icon color on click

mgiurni picture mgiurni · Mar 16, 2018 · Viewed 10k times · Source

I created a component named "like" with the following HTML:

<div (click)="onClick()">
   <i class="fas fa-heart" [class.active]="isActive"></i>
</div>

When I click on the icon, it should change the variable "isActive" and consequently the color of the icon should also change. Here is the .ts:

onClick() {
    this.isActive = !this.isActive;
  }

CSS:

.fa-heart {
    color: #ccc;
}

.fa-heart.active {
    color: deeppink;
}

However, the "active" class is not being added or removed when I click. Why?

Answer

Vitalii Chmovzh picture Vitalii Chmovzh · Mar 16, 2018

You should use the following syntax:

<div (click)="onClick()">
   <i class="fas fa-heart" [ngClass]="{'active': isActive}"></i>
</div>