3

In my Angular4 application, I have a code to conditionally apply two classes that looks like this:

<some-element [ngClass]="{ 'fa-toggle-on': category.active, 'fa-toggle-off': !category.active }">
</some-element>

This works, but is this really the recommended way? It feels a bit unclean to write down category.active twice. I was looking for something more if-else like, but could not find anything so far in the docs and on SO.

FAISAL
  • 33,618
  • 10
  • 97
  • 105
Hinrich
  • 13,485
  • 7
  • 43
  • 66
  • Possible duplicate of [How do you use the ? : (conditional) operator in JavaScript?](https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – Durga Aug 03 '17 at 08:57
  • @Durga Not exactly a duplicate, because this is a Angular specific question. – Hinrich Aug 03 '17 at 09:38

1 Answers1

9

ngClass directive takes an expression. The expression can evaluate to a string.

Here is how to how to use the directive with the string:

<some-element [ngClass]="'first second'">...</some-element>

So in your case use the expression that evaluates to a string:

<some-element [ngClass]="category.active ? 'fa-toggle-on' : 'fa-toggle-off'">
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488