AppDividend
Latest Code Tutorials

Angular NgClass Example | Angular 7 NgClass Tutorial

2

Angular NgClass adds and removes CSS classes on an HTML element. The NgClass directive in Angular allows you to set the CSS class dynamically for the DOM element. The NgClass directive behaves very similar to what ngClass used to do in AngularJS.

If you are new to Angular 7, then check out this Angular 7 CRUD Tutorial article.

Angular 7 NgClass Example

Content Overview

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.

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

Step 1: Install Angular 7 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 NgClass

Alternative syntax of Angular NgClass

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"

Conclusion

Both the NgStyle and NgClass directives can be used to conditionally set the look and feel of your application.

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.

Finally, Angular NgClass Example is over.

Recommended Posts

Angular NgStyle Example

How To Display Data In Angular

Angular Drag and Drop Example

Angular Architecture Overview

Angular Pipes Example

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.