banjocode How To Use Conditional Classes in Angular

How To Use Conditional Classes in Angular

Conditional classes are great. Use one CSS class if one condition is fulfilled, or another class if not. This is a quick guide on how to do that in Angular.

1 min read

Conditional classes

Conditional classes have been possible for a very long time in Angular with the ngClass syntax. There are several different ways to use it.

First version

[class.css-class]="true"

Second version

// single
[ngClass] = "{'css-class': true}"

// multiple same condition
[ngClass] = "{'css-class css-class2': true}"

// multiple different conditions
[ngClass] = "{'css-class': true, 'css-class2': false }";

Third version

[ngClass] = "(true)?'css-class1':'css-class2'";