Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 251
Ajey Avatar asked Apr 03 '17 08:04

Ajey


People also ask

How does angular implement multiple classes?

Angular class binding can also be done to multiple classes by using a generic [class] binding without the dot (for example, [class]="classExpr"). You can format it as an object (object, Array, Map, Set, etc) with class names as the keys and truthy/falsy expressions as the values.

How do I assign multiple classes to an element?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

Can we add two classes in NgClass?

Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class.

Can you assign 2 classes to a div?

Absolutely, divs can have more than one class and with some Bootstrap components you'll often need to have multiple classes for them to function as you want them to. Applying multiple classes of course is possible outside of bootstrap as well. All you have to do is separate each class with a space.


2 Answers

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>
like image 95
Vivek Doshi Avatar answered Oct 13 '22 22:10

Vivek Doshi


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;
  ...
}
like image 23
Alavaros Avatar answered Oct 13 '22 21:10

Alavaros