Problem
What exactly is the issue with my Angular code? This is the error I’m getting:
<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>
Asked by daniel
Solution #1
There are numerous techniques to conditionally add classes in Angular 2+:
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'"
Answered by MostafaMashayekhi
Solution #2
instead of *ngClass, use [ngClass]=…
* is only for structural directives’ shorthand syntax, where you can, for example, use
<div *ngFor="let item of items">{{item}}</div>
lieu of the more lengthy equivalent
<template ngFor let-item [ngForOf]="items">
<div>{{item}}</div>
</template>
See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
See also https://angular.io/docs/ts/latest/guide/template-syntax.html
Answered by Günter Zöchbauer
Solution #3
Another solution would be using [class.active].
Example :
<ol class="breadcrumb">
<li [class.active]="step=='step1'" (click)="step='step1'">Step1</li>
</ol>
Answered by Joel Almeida
Solution #4
The standard structure for ngClass is as follows:
[ngClass]="{'classname' : condition}"
So, in your situation, simply utilize it as follows…
<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>
Answered by Alireza
Solution #5
You can use ‘IF ELSE’ in the following scenarios.
<p class="{{condition ? 'checkedClass' : 'uncheckedClass'}}">
<p [ngClass]="condition ? 'checkedClass' : 'uncheckedClass'">
<p [ngClass]="[condition ? 'checkedClass' : 'uncheckedClass']">
Answered by Chaitanya Nekkalapudi
Post is based on https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass