firasKoubaa firasKoubaa - 3 years ago 202
TypeScript Question

How do I dynamically add two classes using Angular?

I want to add dynamically two classes to a button.

One class is a simple variable reference, and the other needs to use conditional logic.

Here is my code :

<button type="button" class="btn btn-circle btn-xl "
*ngFor="let node of warriorNodesList"
[ngClass]="node.name"
[ngClass]="{'btn-info':node.isLocked == true ,'btn-danger':node.isLocked == false}"
(mouseover)="display($event, node)">
<span>{{node.name}}</span>
</button>


The first class is the
name
property of the
node
variable:

*ngFor="let node of warriorNodesList"
[ngClass]="node.name


The second is a conditional expression:

[ngClass]="{'btn-info':node.isLocked == true ,'btn-danger':node.isLocked == false}


How can I add all of that in only one
ngClass
? It seems that only one
ngClass
gets bound to an element and the other is ignored.

Answer Source

This should do what you want:

[ngClass]="[ node.name, node.isLocked == true ? 'btn-info' : 'btn-danger' ]"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download