Angular 8 ngClass Directive

ngClass Directive is a type of attribute directive. Angular provided built-in directive, and it helps in adding or removing CSS classes on an HTML element. The ngClass directive allows us to apply CSS classes dynamically based on expression evaluation.

[ngClass] selector uses the NgClass directive, and ngClass offers three simple ways through which we can update CSS classes in the DOM.


Create an Interface Class and Array

In this step, we have to create an interface class to define the properties types of cars array.

Run the command to create interface class:

Our cars collection has properties name and color, go to src>app>cars.ts and add the below code:

Then, we will generate the cars array in app.component.ts file same as given below:

Joining NgClass Directive on HTML template

In this last step, we will learn to add the CSS class dynamically to the HTML elements using Angular NgClass directive.


Go to app.component.html template and then add the ngClass directive as mentioned below.

 In the above example, we are representing cars name to apply the dynamic color class, we declared NgClass object expression to apply the class. If the condition is true, it includes the class name on the HTML element if not, then it will discard the class name.

To see the working demo in our browser, run the given command:


Joining NgClass Directive on HTML template

Pin It on Pinterest

Share This