Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to switch classes in Angular

Tags:

angular

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.

like image 574
Hinrich Avatar asked May 31 '26 20:05

Hinrich


1 Answers

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'">
like image 147
Max Koretskyi Avatar answered Jun 03 '26 10:06

Max Koretskyi