bpardo
bpardo

Reputation: 411

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

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>

Upvotes: 4

Views: 6073

Answers (4)

Mathieu Seiler
Mathieu Seiler

Reputation: 747

You can do this:

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

Upvotes: 2

Srinath Kamath
Srinath Kamath

Reputation: 568

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>

Upvotes: 0

kvetis
kvetis

Reputation: 7341

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

Upvotes: 2

Eli
Eli

Reputation: 1846

As specified in: https://angular.io/api/common/NgClass#description You can: <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

Upvotes: 8

Related Questions