Search code examples
angulartypescriptngforng-class

simplify ngClass conditionals that uses ngFor


I have an array with 5 string values excited, happy, neutral, sad, angry

I am using ngClass and ngFor as to simplify the html and so I don't have to repeat everything 5x for each value.

The problem is that the ngClass statement is very bulky and I can't find a proper way to simplify it. Is there any way to make this shorter?

<mat-icon *ngFor="let smiley of smileys" svgIcon="emote_{{smiley}}" 
                [ngClass]="{ happy: smiley === 'happy', sad:  smiley === 'sad', neutral:  smiley === 'neutral', angry:  smiley === 'angry', excited:  smiley === 'excited'}" (click)="selected(smiley, $event)"></mat-icon>

Thank you in advance!


Solution

  • You can simply write

    [ngClass]="smiley"