Categories
Angular Answers

How to add a conditional class with Angular *ngClass and JavaScript?

Spread the love

Sometimes, we want to add a conditional class with Angular *ngClass and JavaScript.

In this article, we’ll look at how to add a conditional class with Angular *ngClass and JavaScript.

How to add a conditional class with Angular *ngClass and JavaScript?

To add a conditional class with Angular *ngClass and JavaScript, we can use the class or ngClass attributes.

For instance, we write

<div [class.my_class]="step === 'step1'"></div>

to set the my_class class when step equals 'step1'.

We can also write

<div [ngClass]="{ my_class: step === 'step1' }"></div>

to do the same thing.

Conclusion

To add a conditional class with Angular *ngClass and JavaScript, we can use the class or ngClass attributes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *