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>
Share:
11,968
mgiurni
Author by

mgiurni

Updated on June 24, 2022

Comments

  • mgiurni
    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
    mgiurni over 6 years
    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.
  • mgiurni
    mgiurni over 6 years
    Yes, it is. I added the line "console.log (this.isActive)" in the method and the variable changes its value when I click.
  • Vitalii Chmovzh
    Vitalii Chmovzh over 6 years
    Is it on clean Angular CLI install ? I've just tried it on clean install and it works.
  • mgiurni
    mgiurni over 6 years
    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.