Home > Enterprise >  How to use class binding with font-awesome icon?
How to use class binding with font-awesome icon?

Time:08-31

I'm trying to display two different icons based on the value of a variable. I want to show up arrow if it's true or down arrow if it's false. But it seems like it's not working at all and I can't figure out why. Here's the code-

<div  (click)="changeValue()">
<i  [ngClass]="isValue ? 'fa-chevron-circle-up' : 'fa-chevron-circle-down'"></i>
</div>

My component class has something like this-

private isValue: boolean = true;
changeValue() {
    this.isValue = !this.isValue;
  }

I don't know why it doesn't work properly. I'm using font-awesome v6 and angular 14. Can anyone help me with this?

CodePudding user response:

Think you're using [ngClass] a bit wrong. Here are the different ways you can do exactly that:

Using [ngClass]:

<i 
   [ngClass]="{ 'fa-chevron-circle-up': isValue, 'fa-chevron-circle-down': !isValue }"
></i>

Using [class.*] binding (my favorite):

<i 
   [class.fa-chevron-circle-up]="isValue"
   [class.fa-chevron-circle-down]="!isValue"
></i>

More docs on class binding can be found here: https://angular.io/guide/class-binding

CodePudding user response:

I switched to angular-fontawesome and it seems to be working with that. ngClass does not work with @fortawesome/[email protected] correctly because the <i> dom is replaced with an <svg> dom. Here's the link to the github issue.

  • Related