Home > Web Front-end > JS Tutorial > Why Does '*ngClass' in Angular Throw a 'Cannot read property 'remove' of undefined' Error?

Why Does '*ngClass' in Angular Throw a 'Cannot read property 'remove' of undefined' Error?

Linda Hamilton
Release: 2024-12-13 12:20:26
Original
805 people have browsed it

Why Does

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
Copy after login
<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>
Copy after login

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'"
Copy after login

Type Two:

[ngClass]="{active: step === 'step1'}"
Copy after login

Type Three:

[ngClass]="{1: 'active', 2: 'step2', 3: 'step3'}[step]"
Copy after login

Type Four:

[ngClass]="step === 'step1' ? 'active' : 'inactive'"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template