Table of contents
1.
Introduction
2.
What is ngClass in Angular? The Basics
2.1.
Key Features
2.2.
Example
3.
Syntax
4.
Using Object Notation:
5.
Using Array Notation
6.
Using String Notation
7.
How to Use ngClass in Angular
8.
How to Use Angular ngClass with a Simple Condition  
8.1.
Example: Using `ngClass` with a Simple Condition  
9.
Angular ngClass and Complex Conditions  
9.1.
Example: Using `ngClass` with Multiple Conditions  
10.
Conditional Class with *ngClass
10.1.
Example
11.
Approach 1: Using Boolean Properties
11.1.
Example
12.
Approach 2: Using Functions
12.1.
Example
13.
[ngClass] vs [class] in Angular
14.
Frequently Asked Questions
14.1.
What is ngClass used for?
14.2.
Can I apply multiple classes using ngClass? 
14.3.
What is the difference between [ngClass] and class binding? 
15.
Conclusion
Last Updated: Jan 20, 2025
Easy

ngClass in Angular

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

ngClass in Angular is a directive that allows developers to dynamically assign CSS classes to an element based on certain conditions. This feature makes it easy to style elements based on the application’s state or user actions. With ngClass, you can apply or remove multiple classes efficiently without hardcoding them in the HTML.

ngClass in Angular

This article will discuss the concept of ngClass, its syntax, and how to use it effectively with examples. 

What is ngClass in Angular? The Basics

ngClass is a built-in Angular directive that allows you to conditionally apply one or more CSS classes to an HTML element. It is particularly useful for dynamic styling based on application state or user interactions. With ngClass, you can easily manage classes using expressions, arrays, or objects.

Key Features

  • Apply multiple classes conditionally.
     
  • Integrate seamlessly with dynamic data.
     
  • Simplify code for complex UI scenarios.

Example

<div [ngClass]="{'active': isActive, 'highlight': isHighlighted}">

This is a dynamically styled div.

</div>

Here, the active class will be applied if isActive is true, and highlight will be applied if isHighlighted is true.

Syntax

The ngClass directive can be used in multiple ways, depending on your application's requirements. Below are the most common syntax formats:

Using Object Notation:

<div [ngClass]="{'class1': condition1, 'class2': condition2}">
  Content here
</div>

 

  • class1 and class2 are the CSS classes.
     
  • condition1 and condition2 are Boolean expressions that determine whether the classes are applied.

Using Array Notation

<div [ngClass]="[condition1 ? 'class1' : '', condition2 ? 'class2' : '']">

  Content here

</div>

Add classes to the array conditionally.

Using String Notation

<div [ngClass]="'class1 class2'">
  Content here
</div>

Directly pass a space-separated string of class names.

How to Use ngClass in Angular

To use ngClass, you need a proper Angular setup. Follow the steps below:

Step 1: Set Up an Angular Project

First, ensure you have Angular CLI installed. Create a new project using:

ng new my-angular-app
cd my-angular-app


Step 2: Define Styles

Add the CSS classes to your component's stylesheet:

.active {
  color: white;
  background-color: green;
}

.highlight {
  font-weight: bold;
  text-decoration: underline;
}


Step 3: Use ngClass in the Component

In the HTML file:

<button (click)="toggleStyles()">Toggle Styles</button>
<div [ngClass]="{'active': isActive, 'highlight': isHighlighted}">
  This text changes style dynamically.
</div>


In the component file:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  isActive: boolean = false;
  isHighlighted: boolean = false;


  toggleStyles() {
    this.isActive = !this.isActive;
    this.isHighlighted = !this.isHighlighted;
  }
}


Output:

When you click the button, the text's styles will toggle between the active and highlight classes.

How to Use Angular ngClass with a Simple Condition  

`ngClass` is a directive in Angular that helps you dynamically apply CSS classes to HTML elements based on certain conditions. It’s especially useful when you want to change the appearance of an element depending on the state of your application. Let’s understand this with a simple example.  

Basic Syntax of `ngClass`  

The `ngClass` directive can be used in two ways:  

1. Object Syntax: Here, you pass an object where the keys are the class names & the values are conditions. If the condition is `true`, the class is applied.  

2. Array Syntax: You can also pass an array of class names, which will be applied unconditionally.  

Example: Using `ngClass` with a Simple Condition  

Let’s say you have a button, & you want to apply a CSS class called `active` when a variable `isActive` is `true`. Let’s see how you can do it:  

1. Step 1: Set Up Your Angular Component  

First, create a new Angular component or use an existing one. In your component’s TypeScript file (`app.component.ts`), define a variable `isActive`:  

   import { Component } from '@angular/core';
  @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
   })
   export class AppComponent {
     isActive: boolean = true; // You can change this value to false to see the difference
   }


2. Step 2: Add CSS Classes  

In your component’s CSS file (`app.component.css`), define the `active` class:  

   .active {
     background-color: green;
     color: white;
   }


3. Step 3: Use `ngClass` in the Template  

In your component’s HTML file (`app.component.html`), use the `ngClass` directive to apply the `active` class conditionally:  

 <button [ngClass]="{ 'active': isActive }">Click Me</button>


Here, `{ 'active': isActive }` is an object where `active` is the class name, & `isActive` is the condition. If `isActive` is `true`, the `active` class will be applied to the button.  


4. Step 4: Test the Output  

Run your Angular application using `ng serve`. If `isActive` is `true`, the button will have a green background & white text. If you change `isActive` to `false`, the button will revert to its default style.  


In this Code: 

- The `ngClass` directive is used inside square brackets (`[]`) because it’s a property binding.  
 

- The object `{ 'active': isActive }` tells Angular to apply the `active` class only if `isActive` is `true`.  
 

- This approach is clean & easy to understand, making it perfect for simple conditions.  

Angular ngClass and Complex Conditions  

While `ngClass` is great for simple conditions, it truly shines when dealing with more complex scenarios. You can use multiple conditions, logical operators, & even functions to determine which classes should be applied. Let’s explore this with an example.  

Example: Using `ngClass` with Multiple Conditions  

Suppose you have a user interface where you want to apply different styles to a button based on two conditions:  

1. Whether the button is active (`isActive`).  
 

2. Whether the button is disabled (`isDisabled`).  
 

Let’s see how you can achieve this:  

1. Step 1: Set Up Your Angular Component  

In your component’s TypeScript file (`app.component.ts`), define the variables `isActive` & `isDisabled`:  

   import { Component } from '@angular/core';

   @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
   })
   export class AppComponent {
     isActive: boolean = true; // Change this to test
     isDisabled: boolean = false; // Change this to test
   }


2. Step 2: Add CSS Classes  

In your component’s CSS file (`app.component.css`), define the classes for different states:  

   .active {
     background-color: green;
     color: white;
   }

   .disabled {
     background-color: gray;
     color: black;
     cursor: not-allowed;
   }

   .default {
     background-color: blue;
     color: white;
   }


3. Step 3: Use `ngClass` with Multiple Conditions  

In your component’s HTML file (`app.component.html`), use `ngClass` to apply classes based on the conditions:  

   <button [ngClass]="{
     'active': isActive && !isDisabled,
     'disabled': isDisabled,
     'default': !isActive && !isDisabled
   }">Click Me</button>


 In this code:  

   - If `isActive` is `true` & `isDisabled` is `false`, the `active` class is applied.  
 

   - If `isDisabled` is `true`, the `disabled` class is applied.  
 

   - If neither `isActive` nor `isDisabled` is `true`, the `default` class is applied.  
 

4. Step 4: Test the Output  

Run your Angular application using `ng serve`. Try changing the values of `isActive` & `isDisabled` in the component file to see how the button’s appearance changes.  


In this Code: 


- The `ngClass` directive now uses an object with multiple key-value pairs. Each key is a class name, & the value is a condition.  
 

- Logical operators like `&&` (AND) & `!` (NOT) are used to create complex conditions.  
 

- This approach allows you to handle multiple states & apply different styles dynamically.  

Conditional Class with *ngClass

The *ngClass directive provides a clean way to conditionally apply classes based on component state.

Example

<ul>
  <li *ngFor="let item of items" [ngClass]="{'selected': item.selected}">
    {{ item.name }}
  </li>
</ul>
In the component:
items = [
  { name: 'Item 1', selected: false },
  { name: 'Item 2', selected: true },
  { name: 'Item 3', selected: false }
];


Explanation:

The selected class will be applied only to items where item.selected is true.

Approach 1: Using Boolean Properties

This approach uses Boolean variables to control class application.

Example

<button [ngClass]="{'btn-primary': isPrimary, 'btn-secondary': !isPrimary}">
  Click Me
</button>
In the component:
isPrimary: boolean = true;


Output:

The button will have the btn-primary class if isPrimary is true, otherwise btn-secondary.

Approach 2: Using Functions

Another approach is to use functions to return the desired class names.

Example

<div [ngClass]="getClassNames()">
  Dynamic Classes
</div>
In the component:
getClassNames() {
  return {
    'class-a': this.conditionA,
    'class-b': this.conditionB
  };
}


Output:

The classes class-a and class-b will be applied based on the return values of conditionA and condition.

[ngClass] vs [class] in Angular

Feature[ngClass][class]
PurposeDynamically add or remove CSS classes based on conditions. Binds class names to expressions or object literals.Statically apply CSS classes to an element. Binds a fixed set of classes to the element.
Syntax[ngClass]="{'class-name': condition}" or [ngClass]="expression"[class]="'class-name'" or [class.class-name]="condition"
Dynamic BindingSupports dynamic binding of classes based on conditions or expressions. Classes can be added or removed dynamically at runtime.Supports static binding of classes. Classes are fixed and cannot be dynamically changed.
Multiple ClassesAllows applying multiple classes using key-value pairs in an object literal or an array of class names.Allows applying multiple classes by specifying them as a space-separated string.
Conditional ClassesSuitable for applying classes conditionally based on component logic or user interactions. Uses boolean expressions, object literals, or functions.Suitable for applying classes unconditionally. Conditional application uses [class.class-name]="condition" syntax.
ReadabilityCan be less readable with complex conditions or multiple classes, making the template more verbose.More readable for applying fixed classes. Clearly shows class names in the template.
PerformanceSlight performance overhead due to dynamic evaluations. Negligible impact unless dealing with many elements.Better performance as it applies classes statically without dynamic evaluations.

Frequently Asked Questions

What is ngClass used for?

 ngClass is used to dynamically add or remove CSS classes on an HTML element based on component logic.

Can I apply multiple classes using ngClass? 

Yes, you can apply multiple classes using object, array, or string syntax.

What is the difference between [ngClass] and class binding? 

class binding is used for a single class, while ngClass is used for conditional and multiple class bindings.

Conclusion

In this article, we explored the ngClass directive in Angular, which is an essential tool for dynamic class manipulation. From its syntax to various approaches, we learned how to apply conditional styling effectively. Mastering ngClass will help you build more interactive and user-friendly applications.

You can also check out our other blogs on Code360.

Live masterclass