Angular - Change Font Awesome icon color on click
11,968
You should use the following syntax:
<div (click)="onClick()">
<i class="fas fa-heart" [ngClass]="{'active': isActive}"></i>
</div>
Author by
mgiurni
Updated on June 24, 2022Comments
-
mgiurni about 2 years
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?
-
mgiurni over 6 yearsThanks 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.
-
mgiurni over 6 yearsYes, it is. I added the line "console.log (this.isActive)" in the method and the variable changes its value when I click.
-
Vitalii Chmovzh over 6 yearsIs it on clean Angular CLI install ? I've just tried it on clean install and it works.
-
mgiurni over 6 yearsI 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.