DEV Community

Cover image for How to add class conditionally to css element in angular
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

3

How to add class conditionally to css element in angular

Use the ngClass input attribute with the object notation, where the keys are CSS classes that get added when the expression given in the value evaluates to truthy value, otherwise they are removed.

In the example below the class navbar-dev-green is added to the nav element only for the dev environment (non-prod):

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top shadow"
     [ngClass]="{'navbar-dev-green' : environment.production === false}" >
...
</nav>
Enter fullscreen mode Exit fullscreen mode

Project: codever - File: navigation.component.html

To add multiple classes you can list them with space between them. To add different conditions for each class use a boolean expression evaluator for each class as shown in the example in the angular documentation:

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

Enter fullscreen mode Exit fullscreen mode


Reference -

https://angular.io/api/common/NgClass


Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Codever is open source on Github⭐🙏

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay