Angular: conditional class with *ngClass Angular: conditional class with *ngClass javascript javascript

Angular: conditional class with *ngClass


Angular version 2+ provides several ways to add classes conditionally:

type one

[class.my_class] = "step === 'step1'"

type two

[ngClass]="{'my_class': step === 'step1'}"

and multiple option:

[ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"

type three

[ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"

type four

[ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"


[ngClass]=... instead of *ngClass.

* is only for the shorthand syntax for structural directives where you can for example use

<div *ngFor="let item of items">{{item}}</div>

instead of the longer equivalent version

<template ngFor let-item [ngForOf]="items">  <div>{{item}}</div></template>

See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

<some-element [ngClass]="'first second'">...</some-element><some-element [ngClass]="['first', 'second']">...</some-element><some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element><some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element><some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

See also https://angular.io/docs/ts/latest/guide/template-syntax.html

<!-- toggle the "special" class on/off with a property --><div [class.special]="isSpecial">The class binding is special</div><!-- binding to `class.special` trumps the class attribute --><div class="special"     [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding  --><div class="bad curly special"     [class]="badCurly">Bad curly</div>


Another solution would be using [class.active].

Example :

<ol class="breadcrumb">    <li [class.active]="step=='step1'" (click)="step='step1'">Step1</li></ol>