简体   繁体   中英

How to use class binding with font-awesome icon?

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 class="custom-class" (click)="changeValue()">
<i class="fa fa-lg " [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?

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

Using [ngClass] :

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

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

<i class="fa fa-lg "
   [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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM