Conditional Class with *ngClass in Angular
Angular provides various options to conditionally apply CSS classes to HTML elements. One common method is using the *ngClass directive. However, if not used correctly, it can lead to errors like "Cannot read property 'remove' of undefined."
Problem:
Given the Angular code below, why is the following error occurring:
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>
Solution:
The error occurs due to the use of the ngClass directive with the conditional expression in Angular version 2 . In Angular 2 , the ngClass directive takes an object as an argument, where the keys represent CSS class names and the values represent boolean expressions.
To resolve this issue, replace the *ngClass directive with any of the following methods provided by Angular:
Type One:
[class.active] = "step === 'step1'"
Type Two:
[ngClass]="{active: step === 'step1'}"
Type Three:
[ngClass]="{1: 'active', 2: 'step2', 3: 'step3'}[step]"
Type Four:
[ngClass]="step === 'step1' ? 'active' : 'inactive'"
For multiple class conditions, you can use the object notation as shown in Type Two. Refer to the Angular documentation for more details on using *ngClass.
The above is the detailed content of Why Does '*ngClass' in Angular Throw a 'Cannot read property 'remove' of undefined' Error?. For more information, please follow other related articles on the PHP Chinese website!