Home > Web Front-end > JS Tutorial > How to Correctly Use `ngClass` for Conditional Styling in Angular?

How to Correctly Use `ngClass` for Conditional Styling in Angular?

Barbara Streisand
Release: 2024-12-27 17:56:15
Original
744 people have browsed it

How to Correctly Use `ngClass` for Conditional Styling in Angular?

Conditional Class with *ngClass in Angular

One of the common requirements in Angular applications is to apply classes conditionally based on certain conditions. The ngClass directive provides a convenient way to achieve this.

Issue Encountered

You may encounter an error like "Cannot read property 'remove' of undefined" when using ngClass in a particular way. This error indicates an incorrect usage of the directive.

Correct Usage of ngClass in Angular 2

Angular 2 and above offers several options for applying conditional classes:

Option 1:

[class.my_class] = "step === 'step1'"
Copy after login

This syntax adds the 'my_class' class only if the 'step' variable equals 'step1'.

Option 2:

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

This option uses an object literal to specify the condition and the corresponding class to be applied.

Option 3:

[ngClass] = "{'1' : 'my_class1', '2' : 'my_class2', '3' : 'my_class4'}[step]"
Copy after login

This method utilizes a hash lookup to apply the appropriate class based on the value of the 'step' variable.

Option 4:

[ngClass] = "step == 'step1' ? 'my_class1' : 'my_class2'"
Copy after login

This syntax uses the ternary operator to conditionally set the class based on the 'step' variable.

Example

In your code, you stated using ngClass={active: step==='step1'}, which is not the correct syntax. Instead, use one of the options outlined above. For example:

<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

Adopting one of these alternative approaches should resolve the error you were encountering. Refer to the Angular documentation for further details.

The above is the detailed content of How to Correctly Use `ngClass` for Conditional Styling in Angular?. 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