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.
ngClass for dynamic classes in 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.
<div [ngClass]="'active'">Content</div><div [ngClass]="['class1', 'class2']">Content</div><div [ngClass]="{ 'highlight': isActive, 'error': hasError }">Content</div>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.
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; } }
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.
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.