Angular 2 add multiple classes via [class.className] binding

JavascriptAngularBinding

Javascript Problem Overview


While adding a single class works great in this way -

[class.loading-state]="loading"

But how do I add multiple classes Ex if loading is true add class - "loading-state" & "my-class"

How do I get it done via the [class] binding

Javascript Solutions


Solution 1 - Javascript

You can do this by simply using ngClass :

Here first,second and third are the name of the classes.

And instead of true/false , you can directly put your conditions over there

 <div [ngClass]="{'first': true, 'second': true, 'third': false}">...</div>

In your case

 <div [ngClass]="{'loading-state': loading, 'my-class': loading }">...</div>

Or Shorter Veriosn (as @matko.kvesic commented)

<div [ngClass]="{'loading-state my-class': loading}">...</div>

Solution 2 - Javascript

Although Vivek Doshi answer is totally correct, below I put other alternatives to do the same with different boolean variables:

1st Solution: [class.className]

Template:
<div [class.first-class]="addFirst" [class.second-class]="addSecond">...</div>
Component:
export class MyComponent {
  ...
  addFirst: boolean;
  addSecond: boolean;
  ...
}

2nd Solution: [ngClass] with method binding

Template:
<div [ngClass]="setClasses()">...</div>
Component:
export class MyComponent {
  ...
  addFirst: boolean;
  addSecond: boolean;
  ...
  setClasses() {
    return {
      'first-class': this.addFirst,
      'second-class': this.addSecond
    };
  }
  ...
}

Last solution, but not least:

Template:
<div [ngClass]="{'first-class': addFirst, 'second-class': addSecond}">...</div>
Component:
export class MyComponent {
  ...
  addFirst: boolean;
  addSecond: boolean;
  ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjeyView Question on Stackoverflow
Solution 1 - JavascriptVivek DoshiView Answer on Stackoverflow
Solution 2 - JavascriptAlavarosView Answer on Stackoverflow