Angular NgClass Example
December 30, 2020
On this page we will provide Angular NgClass
example. It is used to add and remove CSS classes on an HTML element. We can bind several CSS classes to NgClass
simultaneously that can be added or removed. There are different ways to bind CSS classes to NgClass
that are using string, array and object. CSS classes are assigned to NgClass
as property binding using bracket i.e [ngClass]
as attribute of any HTML element. We can assign one or more than one CSS classes to HTML element using NgClass
. When we use NgClass
with object then adding and removing CSS classes are performed on the basis of retuned Boolean value of an expression. If the value of expression is true then respective CSS class will be added otherwise that CSS class will be removed from HTML element at run time. Now we will discuss here NgClass
example in detail step by step using TypeScript.
Contents
Technologies Used
Find the technologies being used in our example.1. Angular 11.0.3
2. Node.js 12.5.0
3. NPM 6.9.0
Create CSS Classes
For the demo we are creating four CSS classes as follows..one { color: green; } .two { font-size: 20px; } .three { color: red; } .four { font-size: 15px; }
NgClass with String
We have two CSS classes named as .one and .two. Now to bind CSS class toNgClass
, just create a string and inside it we need to refer our CSS class names enclosed by single quote ('). Find the code below. Here we are binding a single CSS class to NgClass
.
<p [ngClass]="'one'"> Using NgClass with String. </p>
<p [ngClass]="'one two'"> Using NgClass with String. </p>
ngClass
with ngFor
using string as follows. The given CSS classes will be applied to HTML element in each iteration.
<div *ngFor="let user of users" [ngClass]="'one two'"> {{user}} </div>
NgClass with Array
Here we will discuss how to useNgClass
with array of CSS classes. Suppose we have two CSS classes named as .one and .two. We need to add our CSS classes within bracket [ ] separated by comma (,) and enclosed by single quotes (').
<p [ngClass]="['one', 'two']"> Using NgClass with Array. </p>
ngClass
with array can also be used with ngFor
as follows.
<div *ngFor="let user of users" [ngClass]="['one', 'two']"> {{user}} </div>
NgClass with Object
Here we will discussNgClass
with object using braces { }. It will be in key and value pair format separated by colon (:).
key: CSS class name.
value: An expression that returns Boolean value.
Here key will be CSS class name and value will be an expression that will return Boolean value. CSS will be added at run time in HTML element only when if expression will return true. If expression returns false then the respective CSS class will not be added. Suppose we have four CSS classes named as .one, .two, .three and .four. Now find the below code snippet.
<p [ngClass]="{'one': true, 'three': false }"> Using NgClass with Object. </p>
.one
is true. So this CSS class will be added at runtime. Now check next CSS class used in above code snippet that is .three
and its expression value is false. So this CSS class will be removed at run time from HTML element.
ngClass
with object can also be used with ngFor
. Find the code snippet below. Here we are using index
variable and dividing it by 2 in every iteration. When the result is 0, we are using CSS class as .one
and if result is 1 then we are using CSS class as .three
.
<div *ngFor="let user of users; let i = index"> <div [ngClass]="{'one': i%2==0, 'three':i%2==1}"> {{user}} </div> </div>
even
variable. This variable returns true if iteration number is even otherwise false.
<div *ngFor="let user of users; let flag = even;"> <div [ngClass]="{'one':flag, 'two':flag, 'three':!flag, 'four':!flag}"> {{user}} </div> </div>
flag
value is true then CSS classes .one
and .two
will be added to the HTML element otherwise CSS classes .three
and .four
will be added to HTML element at run time.
NgClass with Component Method
Here we will use a component method withNgClass
. We will create a component method that will return a set of CSS classes. We can dynamically add or remove CSS classes from our set within the method. Find the component method used in our example.
getCSSClasses(flag:string) { let cssClasses; if(flag == 'nightMode') { cssClasses = { 'one': true, 'two': true } } else { cssClasses = { 'two': true, 'four': false } } return cssClasses; }
NgClass
. We can easily add or remove CSS classes in our set dynamically within component method. We will call our component method with NgClass
as below.
<div [ngClass]="getCSSClasses('nightMode')"> Using NgClass with Component Method. </div>
getCSSClasses()
method that will return a set of CSS classes to NgClass
on the basis of specified argument.
Complete Example
app.component.css.one { color: green; } .two { font-size: 20px; } .three { color: red; } .four { font-size: 15px; }
<p [ngClass]="'one two'"> Using NgClass with String. </p> <p [ngClass]="['three', 'four']"> Using NgClass with Array. </p> <p [ngClass]="{'one': true, 'three': false }"> Using NgClass with Object. </p> <div *ngFor="let user of users; let flag = even;"> <div [ngClass]="{'one':flag, 'two':flag, 'three':!flag, 'four':!flag}"> {{user}} </div> </div> <br/> <div [ngClass]="getCSSClasses('nightMode')"> Using NgClass with Component Method. </div>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { users = [ 'Mahesh', 'Krishna', 'Narendra', 'Jitendra' ]; getCSSClasses(flag: string) { let cssClasses; if (flag == 'nightMode') { cssClasses = { 'one': true, 'two': true } } else { cssClasses = { 'two': true, 'four': false } } return cssClasses; } }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], providers: [ ], bootstrap: [ AppComponent ] }) export class AppModule { }
Run Application
To run the application, find the steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.
