The ngClass directive in Angular is “used to add and remove CSS classes on an HTML element.”
Angular ngClass Properties
Property | Description |
---|---|
@Input(‘class’) class: string |
Write-Only |
@Input() ngClass: string | string[] | Set<string> | { [class: string]: any; } |
Write-Only |
You can update the CSS classes based on the type of expression selection.
- String – The CSS classes listed in the string (space-delimited) are added,
- Array – The CSS classes declared as the Array elements are added,
- Object – The keys are CSS classes that get added when the expression given in the value evaluates the true value. If false, then they are removed.
The selector of the NgClass directive is [ngClass]. Depending on the type of evaluation, we will assign the class values to this ngClass directive.
One of the primary use cases of NgClass is that we can toggle the class on or off, depending on the application’s state with NgClass.
Before that, we look at how CSS classes are assigned using regular JavaScript and then compare that to the angular way.
NgClass Method
ngDoCheck()
The ngDoCheck() is a callback method that performs change-detection invoked after the default change-detector runs.
Angular doCheck() is a lifecycle hook that invokes the custom change-detection function for the directive in addition to the check performed by the default change-detector.
Here is the step-by-step guide to Add Conditional CSS Classes in Angular.
Step 1: Install the Angular Application
You need to update your CLI if you do not have the latest Angular CLI. For more guidance, see this tutorial.
Now, create a new project using the following command.
Go inside the folder and open the folder in Visual Studio Code.
Install the Bootstrap 4 CSS Framework using the following command.
npm install bootstrap --save
Add the bootstrap CSS file inside the angular.json file.
"styles": [ "src/styles.css", "./node_modules/bootstrap/dist/css/bootstrap.min.css" ],
Step 2: Create a Model file.
Inside the src >> app folder, create a Singer.ts file and add the following code inside it.
// Singer.ts export default class Singer { artist: String; country: String; }
Write the following code inside an app.component.ts file.
// app.component.ts import { Component } from '@angular/core'; import Singer from './Singer'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { singers: Singer[] = [ { 'artist': 'Michael Jackson', 'country': 'USA' }, { 'artist': 'Justin Bieber', 'country': 'Canada' }, { 'artist': 'Daddy Yankee', 'country': 'Purto Rico' }, { 'artist': 'A R Rehman', 'country': 'India' }, { 'artist': 'Selena Gomez', 'country': 'USA' } ]; }
Step 3: Put NgClass directive on the HTML page
Write the following code inside the app.component.html file.
<!-- app.component.html --> <div class="container"> <h4>NgClass</h4> <div *ngFor="let celeb of singers"> <p [ngClass]="{ 'text-success':celeb.country === 'USA', 'text-secondary':celeb.country === 'Canada', 'text-danger':celeb.country === 'Puorto Rico', 'text-info':celeb.country === 'India' }">{{ celeb.artist }} ({{ celeb.country }}) </p> </div> </div>
Save the file, go to the terminal, and start the Angular development server.
ng serve --open
It will open the browser, and now you can see that we can see the different text colors according to Singer’s country.
Alternative syntax of Angular NgClass
Like other single-page application frameworks, Angular shines regarding data binding. The DOM is automatically updated whenever the corresponding JavaScript object changes. This is the same for the CSS classes.
We can also set the class on an element by binding to the class input property, like [class]=” ‘text-info'”.
One thing to note is that the ‘text-info’ is wrapped with single quotes, so it doesn’t treat text-success as a variable when evaluated as javascript.
To add the text-info to the list of classes already set on the item, we can use the extended syntax [class.<class-name>]=’correct expression’.
[class.text-info] = "true"
How to toggle CSS classes in Angular
The syntax above is inconvenient when toggling CSS classes based on a condition.
A better way to do this is by using the class.name directive. With that directive, we can easily toggle CSS classes like so.
<div [class.example-class]="condition"></div>
As you can see, this directive starts with the keyword “class,” followed by the name of the CSS class you want to toggle, separated by a dot. While this syntax is not much shorter, it has the advantage that its meaning is clear at first sight: We want to toggle a class.
Using the general syntax shown in the previous chapter is not the case. The programmer has to read the whole statement before it is clear what it does.
Using the ngClass directive for convenience
The ngClass directive can replace all the methods we discovered above.
This directive is just syntactic sugar to make the code look more streamlined. In some cases, it is also shorter or more convenient to use.
The directive itself is very versatile. Depending on the input, it can do a lot of different things.
For example, if we just wanted to assign a static class name, we would like the following.
<div [ngClass]="'example-class'"></div>
That’s it for this tutorial.
Dharma
Very neat and clean tutorial. Thank for your efforts for Angular [ngClass] attribute directives. Keep it up.
Android example
i want ngClass for col in bootstrap do what
Garcin
Excellent Tutoriel, franchement, c’est clair et limpide
Merci