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.
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'">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With