Angular - Change Font Awesome icon color on click
Asked Answered
T

1

7

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?

Tomasz answered 16/3, 2018 at 0:31 Comment(3)
Did u import the CommonModule in your module?Aridatha
It works fine: stackblitz.com/edit/angular-3xkkbfKaden
Voting to close this as per your last comment on @VitaliiChmovzh's answer.Kaden
W
3

You should use the following syntax:

<div (click)="onClick()">
   <i class="fas fa-heart" [ngClass]="{'active': isActive}"></i>
</div>
Weide answered 16/3, 2018 at 0:33 Comment(4)
Thanks for the answer. However, it still did not work. The "active" class is only added or removed depending on how the "isActive" variable starts, but not when I click.Tomasz
Yes, it is. I added the line "console.log (this.isActive)" in the method and the variable changes its value when I click.Tomasz
Is it on clean Angular CLI install ? I've just tried it on clean install and it works.Weide
I found the problem. I was using Font Awesome through its CDN. I downloaded it in my project and it worked. Thank you very much for your effort to help me.Tomasz

© 2022 - 2024 — McMap. All rights reserved.