NgClass in Angular

Written by: Arvind Rai,
Last updated:
March 25, 2024
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.

1. 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;
}
.darkMode {
    background-color: black;
    color: white;
}
.lightMode {
    background-color: white;
    color: black;
} 

2. NgClass with String

We have two CSS classes named as .one and .two. Now to bind CSS class to NgClass, 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>  
In case we want to add more than one CSS classes then add it separated by space.
<p [ngClass]="'one two'">
Using NgClass with String.
</p>  
We can also use 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>  

3. NgClass with Array

Here we will discuss how to use NgClass 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>  

4. NgClass with Object

Here we will discuss NgClass 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>  
In the above code snippet we are using two CSS classes. The expression value of CSS class .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.
TS Code:
users = ['Trump','John','Narendra', 'Bob']; 
HTML Code:
<div *ngFor="let user of users; let i = index">
   <div [ngClass]="{'one': i%2==0, 'three':i%2==1}"> {{user}} </div>
</div>  
Now find the below code snippet. Here we are using 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>  
In the above code snippet, while iteration if 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.

5. NgClass with Conditions

I have a boolean flag in TS file as below.
isDark = true; 
1. Using ternary operator :
<div [ngClass]="isDark ? 'darkMode' : 'lightMode'">
  Applying CSS conditionally
</div> 
When isDark is true, the CSS class darkMode will be applied on <div> element and if isDark is false, the CSS class lightMode will be applied.

2. Using if and else : Create a method in TS file to decide CSS class using if and else condition.
getCSSClassForMode(isDark: boolean) {
	if (isDark) {
		return 'darkMode';
	} else {
		return 'lightMode';
	}
} 
Now use this method to apply CSS dynamically as below.
<div [ngClass]="getCSSClassForMode(isDark)">
  ------
</div> 

3. Using conditions with Object : We know that when we use Object for applying CSS with ngClass, keys are CSS classes and value is truthy value. CSS classes are added when value is true. CSS classes are removed when value is false.
<div [ngClass]="{'darkMode': isDark, 'lightMode': !isDark }">
   ------
</div> 
When ‘isDark’ is ‘true’, CSS class ‘darkMode’ is applied. When ‘isDark’ is ‘false’, CSS class ‘lightMode’ is applied.

4. Create Object for CSS class dynamically in TS file : Here we will use a component method with NgClass. 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;
}	
We will observe that we can create a set of classes that will returned by method. In this way in one call of method we can assign more than one CSS classes to 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> 
In the above code we are calling getCSSClasses() method that will return a set of CSS classes to NgClass on the basis of specified argument.

6. Class Name From Variable

Assign class names to component property and then use property binding with ngClass.
TS:
cssClassName ="darkMode";
setCSSClass(cssClass: string) {
	this.cssClassName = cssClass;
} 
HTML:
<div [ngClass]="cssClassName">
 ------
</div> 
On calling setCSSClass() method, we can set another CSS class name to cssClassName variable dynamically.

7. Using Multiple Classes

Multiple classes can be assigned using string, array and object. Suppose I have three CSS classes as class1, class2 and class3.
1. With String :
Pass class names with space.
<div [ngClass]="'class1 class2 class3'">
  ------
</div> 
2. With Array:
Pass class names as an array.
<div [ngClass]="['class1', 'class2', 'class3']">
  ------
</div> 
3. With Object.
Pass class names as keys and keep value as ‘true’. All the classes with value ‘true’ will be added to the element.
<div [ngClass]="{'class1': true, 'class2': true, 'class3': true }">
  ------
</div> 
Using Object, multiple classes can also be added as below.
<div [ngClass]="{'class1 class2 class3': true}">
  ------
</div> 

8. NgClass vs NgStyle

1. NgClass directive adds or removes CSS classes from an HTML element whereas NgStyle updates styles for the containing HTML element.

2. NgClass adds class attribute to HTML element.
Suppose we have a CSS class as below.
.myClass {
    color: black;
    font-size: 10px;
} 
Bind the class to HTML using ngClass.
<div [ngClass]="'myClass'">
  ------
</div> 
When we run the Angular application and inspect the HTML code, we will see that a class attribute is added to element as below.
<div class="myClass">
  ------
</div> 

3. NgStyle adds style attribute to HTML element.
Suppose we are using ngStyle as below.
<div [ngStyle]="{'color': 'black', 'font-size': '10px'}">
 ------
</div> 
It will add style attribute to element as below.
<div style="color: black; font-size: 10px;">
  ------
</div> 

9. Reference

Join the Newsletter

(Subscribe to get our latest content directly into your inbox)

WRITTEN BY
ARVIND RAI
ARVIND RAI









©2024 concretepage.com | Privacy Policy | Contact Us