1

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!

Pim Schwippert
  • 453
  • 7
  • 18

3 Answers3

5

You can simply write

[ngClass]="smiley"

Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36
  • Simple and efficient ! –  Feb 07 '19 at 08:06
  • wow yes this indeed worked! I thought i had tried it before but I did {{smiley}} instead, which did not work. Thank you! – Pim Schwippert Feb 07 '19 at 08:08
  • To be more clear, using "[ ]" in the template define that you use the variable name instead of value, so [ngClass]="smiley" equal to ngClass="{{smiley}}" – Nguyen Phong Thien Feb 07 '19 at 08:54
  • Very nice what is also possible is to add multiple smilies. By using `[ngClass]="[smiley1, smiley2]"` After this I also noticed it can be unlimted by making `smiley = ['happy', 'sad', 'neutral']` aka `smiley.push('happy')` and keep the `[ngClass]="smiley"`. – Swoox Feb 07 '19 at 10:07
0

make the smileys array content be smarter, encapsulate the concrete class inside the smiley and use it in assignment to the class resolve.

Ilan
  • 2,762
  • 1
  • 13
  • 24
0

Put this part into a function happy: smiley === 'happy', sad: smiley === 'sad', neutral: smiley === 'neutral', angry: smiley === 'angry', excited: smiley === 'excited', maybe a switch or if clauses and return the css-class-name from there.

Then you could write: [ngClass]="determineHappiness()

There is a question solving something similar: check this one out

Kristóf Tóth
  • 791
  • 4
  • 19