The NgClass directive in Angular is used to set a CSS class dynamically based on custom conditions. It behaves very similarly to what ngClass used to do in AngularJS.
If you are new to Angular, check out this Angular CRUD article.
Angular NgClass
Angular NgClass is a built-in directive that allows you to set the CSS class dynamically for the DOM element. The NgClass directive adds and removes 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 most primary use cases of NgClass is that we can toggle the class on or off, depending on the state of the application with NgClass.
Before we do 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.
Class implementation
- NgClass
- NgForOf
- NgStyle
- NgSwitchCase
- UpgradeComponent
Okay, now let’s see the NgClass directive in action.
Step 1: Install the Angular Application
If you do not have the latest Angular CLI, you need to update your CLI. For more guidance, see this tutorial.
Now, create a new project using the following command.
Now, go inside the folder and open the folder in Visual Studio Code.
Next, install the Bootstrap 4 CSS Framework using the following command.
npm install bootstrap --save
Now, 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; }
So, our data array has two properties. 1) artist, 2) country.
Now, 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' } ]; }
So, based on data, we assign the classes to the HTML page, and to do that, we need to use the NgClass directive.
Step 3: Put NgClass directive on HTML page
In the app.component.html file, we need a conditional rendering.
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>
Here, we have used the Object valuation where keys are CSS classes that get added when the expression given in the value evaluates to a truthy value. Otherwise, they are removed.
I have compared Singer’s country, and it will assign that particular text class if it matches.
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 when it comes to data-binding. That means that 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 input property called class, like [class]=” ‘text-info'”.
Here one thing to note is that the ‘text-info’ is wrapped with single quotes, so when it’s evaluated as javascript, it doesn’t treat text-success as a variable.
If we want 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’
See the following code snippet.
[class.text-info]="true"
How to toggle CSS classes in Angular
The syntax shown above is quite inconvenient when it comes to 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
It turns out 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>
Conclusion
Angular version 2,…,10 provides several ways to add classes conditionally; let’s see one by one type.
type one
[class.myClass]="prop === 'prop'"
type two
[ngClass]="{'myClass': prop === 'prop'}"
and multiple options:
[ngClass]="{'myClass': prop === 'prop', 'myClass2':prop === 'prop' }"
type three
[ngClass]="{1:'myClass1',2:'myClass2',3:'myClass4'}[prop]"
type four
[ngClass]="(prop=='prop')?'my-class1':'my-class2'"
Both the NgStyle and NgClass directives can be used to set the look and feel of your application conditionally.
NgStyle gives you fine-grained control on individual properties, but if you want to make changes to multiple properties at once, creating a class that bundles those properties and adding the class with
NgClass makes more sense.
Very neat and clean tutorial. Thank for your efforts for Angular [ngClass] attribute directives. Keep it up.
i want ngClass for col in bootstrap do what