[ng-class]Add multiple classes with a single condition

Viewed 1439

Is it possible to add multiple classes with [ng-class] with a single condition?

Something like this:

<div [ngClass]="Cond ? 'class1, class2' : 'class3, class4'"></div>
4 Answers

You can do this:

<div [ngClass]="{'class1 class2' : condition, 'class3': !condition"}></div>

You have it almost right, just ditch the commas:

<div [ngClass]="Cond ? 'class1 class2' : 'class3 class4'"></div>

Try it on stackblitz.com - I wrote an example.

enter image description here

It is very easy. Steps

  1. Create a boolean for controlling the class binding condition

public hasError: boolean = false;

  1. Create an object with class names as follows
public classObj: any = {
    "classA": !this.hasError,
    "classB": this.hasError,
    "classC": !this.hasError,
    // how much ever class you want
}
  1. Finally use ngClass directive for binding the classObj

<h2 [ngClass]="classObj">Hey, I have a lot of classes!</h2>

Related