AppDividend
Latest Code Tutorials

Angular NgClass Example | NgClass in Angular 9/10

2

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, then check out this Angular CRUD article.

Angular NgClass

Angular NgClass is an inbuilt directive that allows you to set the CSS class dynamically for the DOM element. 

Angular ngClass Properties

PropertyDescription
@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 the expression selection.

  1. String – The CSS classes listed in the string (space-delimited) are added,
  2. Array – The CSS classes declared as the Array elements are added,
  3. Object – The keys are CSS classes that get added when the expression given in the value evaluates to 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 take a 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

  1. NgClass
  2. NgForOf
  3. NgStyle
  4. NgSwitchCase
  5. UpgradeComponent

Okay, now let’s see the NgClass directive in action.

Step 1: Install the Angular 10 Application

If you do not have the latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial.

Now, create a new project using the following command.

Install Angular 7 Application

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 one file called 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, here, 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 if match, then it will assign that particular text class.

Save the file and go to the terminal and start the Angular development server.

ng serve --open

It will open the browser, and now you can see that according to Singer’s country, we can see the different text colors.

Angular 7 NgClass Tutorial With Example | Angular NgClassAlternative syntax of Angular NgClass

Angular, like other single-page application frameworks, really 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 binding called class, like so [class]=”‘text-info'”.

Here one thing to note that the ‘text-info’ is wrapped with single quotes, so when it’s evaluated as javascript, it doesn’t try to 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

When it comes to toggling CSS classes based on a condition, the syntax shown above is quite inconvenient.

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, that is not the case. The programmer has to read the whole statement first before it is clear what it does.

Using the ngClass directive for convenience

It turns out, all the methods we discovered above can be replaced by the ngClass directive.

This directive is just syntactic sugar to make the code look more streamlined. In some cases, it is also shorter or convenient to use, as well.

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 do so 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.

2 Comments
  1. Dharma says

    Very neat and clean tutorial. Thank for your efforts for Angular [ngClass] attribute directives. Keep it up.

  2. Android example says

    i want ngClass for col in bootstrap do what

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.