5

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?

HDJEMAI
  • 7,766
  • 41
  • 60
  • 81
mgiurni
  • 145
  • 1
  • 2
  • 8

1 Answers1

3

You should use the following syntax:

<div (click)="onClick()">
   <i class="fas fa-heart" [ngClass]="{'active': isActive}"></i>
</div>
Vitalii Chmovzh
  • 2,495
  • 4
  • 12
  • 24
  • 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 Mar 16 '18 at 00:40
  • Yes, it is. I added the line "console.log (this.isActive)" in the method and the variable changes its value when I click. – mgiurni Mar 16 '18 at 00:43
  • Is it on clean Angular CLI install ? I've just tried it on clean install and it works. – Vitalii Chmovzh Mar 16 '18 at 01:38
  • 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. – mgiurni Mar 16 '18 at 01:57