Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Angular: conditional class with *ngClass

What's going on with my Angular code? I'm getting the accompanying blunder:

Cannot read property 'remove' of undefined at BrowserDomAdapter.removeClass
<ol>
<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>
by

2 Answers

kshitijrana14
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'"
sandhya6gczb
That's the normal structure for ngClass is:

[ngClass]="{'classname' : condition}"

just use this

<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>

Login / Signup to Answer the Question.