Conditional css class in angular html element

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}" >

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 of the documentation:

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

Reference -

Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading