0
0
Angularframework~5 mins

ngClass for dynamic classes in Angular

Choose your learning style9 modes available
Introduction

ngClass helps you add or remove CSS classes on HTML elements easily based on conditions. It makes your page look different depending on your data or user actions.

You want to highlight a button when it is clicked.
You want to show an error style only when a form input is invalid.
You want to change the color of a list item based on its status.
You want to toggle multiple styles on an element depending on user choices.
Syntax
Angular
<element [ngClass]="expression"></element>

The expression can be a string, array, or object.

Use object syntax to add classes conditionally with true/false values.

Examples
Adds the class 'active' always.
Angular
<div [ngClass]="'active'">Content</div>
Adds multiple classes from an array.
Angular
<div [ngClass]="['class1', 'class2']">Content</div>
Adds 'highlight' if isActive is true, 'error' if hasError is true.
Angular
<div [ngClass]="{ 'highlight': isActive, 'error': hasError }">Content</div>
Sample Program

This component has a button that changes its background color when clicked by toggling the 'active' and 'inactive' classes. Another paragraph shows an error style when the 'hasError' flag is true. The second button toggles this error style.

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

@Component({
  selector: 'app-dynamic-class',
  template: `
    <button (click)="toggleActive()" [ngClass]="{ active: isActive, inactive: !isActive }">
      Click me
    </button>
    <p [ngClass]="{ error: hasError }">This is a message.</p>
    <button (click)="toggleError()">Toggle Error</button>
  `,
  styles: [
    `.active { background-color: lightgreen; }`,
    `.inactive { background-color: lightgray; }`,
    `.error { color: red; font-weight: bold; }`
  ]
})
export class DynamicClassComponent {
  isActive = false;
  hasError = false;

  toggleActive() {
    this.isActive = !this.isActive;
  }

  toggleError() {
    this.hasError = !this.hasError;
  }
}
OutputSuccess
Important Notes

ngClass updates classes automatically when the bound expression changes.

Use meaningful class names and keep styles in CSS for better separation.

Remember to import CommonModule in your Angular module to use ngClass.

Summary

ngClass lets you add or remove CSS classes dynamically in Angular templates.

You can use string, array, or object syntax to control classes.

It helps make your UI respond visually to data or user actions easily.