18

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>
Ramana Sarva
  • 293
  • 2
  • 5
  • 20

2 Answers2

48

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

Loolooii
  • 8,588
  • 14
  • 66
  • 90
eltonkamami
  • 5,134
  • 1
  • 22
  • 30
  • That worked! Thanks @eltonkamami. As a follow-up question, is there some place I can read about specific syntaxes like these for Angular 2? – Ramana Sarva Aug 28 '16 at 21:19
  • @RamanaSarva https://angular.io/cheatsheet this is the official angular 2 cheatsheet covering a lot of ng2 syntax – eltonkamami Aug 28 '16 at 21:51
  • Class names in this case should be inside single brackets. I will update the answer. – Loolooii Mar 23 '17 at 12:03
2

Angular 2 provide some way to add class with the condition , this link is helpful

Angular 2 conditional class with *ngClass

Community
  • 1
  • 1
MostafaMashayekhi
  • 27,359
  • 3
  • 21
  • 39