Angular 8 ngClass Directive
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.
Syntax:
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:
ng generate class Cars
Our cars collection has properties name and color, go to src>app>cars.ts and add the below code:
export interface Cars { name: string; color: string; }
Then, we will generate the cars array in app.component.ts file same as given below:
Import {Component} from ‘@angular/core’; Import {Cars} from ‘./cars’; @Component({ selector: ‘app-root’, templateUrl:’./app.component.html’, styleUrls: [‘./app.component.css’] }) export class AppComponent { cars: Cars[]=[ { “name”:”MG Hector”, “color”: ’blue’ }, { “name”:”Ford”, “color”: ’olive’ }, { “name”:”Kia”, “color”: ’orange’ }, { “name”:”BMW”, “color”: ’red’ }, { “name”:”Jaguar”, “color”: ’Green’ }, { “name”:”Suzuki”, “color”: ’purple’ } ]; }
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.
Example:
Go to app.component.html template and then add the ngClass directive as mentioned below.
{{car.name}]
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:
ng serve --open
Output: