Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign classes conditionally in Angular2 [duplicate]

I'm trying to conditionally assign a class to a div based on the value I obtained from my back-end system.

Say there is an object 'A' which has a variable status which possibly has values status1 and status2.

I'm trying to assign 2 classes (class1 and class2) conditionally depending on the status using Angular 2. Following is the condition I'm using. Please suggest a working alternative for this,

<div ng-class="{status1 : 'class1', status2 : 'class2'}[A.status]">
   ...
</div>
like image 339
Ramana Sarva Avatar asked Aug 28 '16 21:08

Ramana Sarva


People also ask

How do you add conditions to NgClass?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can you use NgClass and class?

You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.


1 Answers

You can bind your object to the [ngClass] directive

<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">

almost the same syntax as angular 1. just add the square brackets

like image 162
eltonkamami Avatar answered Sep 21 '22 14:09

eltonkamami