Angular: conditional class with *ngClass

daniel picture daniel · Feb 8, 2016 · Viewed 865.5k times · Source

What is wrong with my Angular code? I am getting:

Cannot read property 'remove' of undefined at BrowserDomAdapter.removeClass ...

HTML

<ol class="breadcrumb">
    <li *ngClass="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
    <li *ngClass="{active: step==='step2'}"  (click)="step='step2'">Step2</li>
    <li *ngClass="{active: step==='step3'}" (click)="step='step3'">Step3</li>
</ol>

Answer

MostafaMashayekhi picture MostafaMashayekhi · Feb 1, 2017

Angular version 2,...,9 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'"