Dynamically Adding Classes with ngClass in Angular

kavindukarunasena

Kavindu Karunasena

Posted on April 23, 2024

Dynamically Adding Classes with ngClass in Angular

Angular's ngClass directive allows you to conditionally apply CSS classes to HTML elements based on data or expressions within your component. This provides a powerful way to control the element's appearance dynamically.

Template:

<div [ngClass]="myClasses">This element's classes change dynamically!</div>

Enter fullscreen mode Exit fullscreen mode
import { Component } from '@angular/core';

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

  constructor() {
    this.myClasses = {
      'highlight': this.isActive, // Class applied based on condition
      'large': true // Always applied class
    };
  }

  toggleActive() {
    this.isActive = !this.isActive;
    this.myClasses = {
      'highlight': this.isActive,
      'large': true
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. The [ngClass] directive binds an object (myClasses) to the element's class attribute.
  2. The myClasses object contains key-value pairs where the key is the CSS class name and the value is a boolean expression.
  3. A class is added to the element only if the corresponding value in myClasses evaluates to true.
  4. You can update the myClasses object in your component's methods (e.g., toggleActive) to dynamically change the applied classes.

Additional Options:

  • String: You can use a space-separated string to define multiple classes that are always applied.
  • Array: An array of strings or objects allows for combining different approaches within ngClass.

  • Remember:

  • ngClass offers flexibility for conditional class application.

  • Ensure your CSS classes are defined for proper styling effects.

This approach provides a versatile way to manage class names based on your application's logic, making your Angular components more dynamic and responsive.

💖 💪 🙅 🚩
kavindukarunasena
Kavindu Karunasena

Posted on April 23, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related