Angular add class dynamically

Angular Add Class Dynamically

If you want to add a class to an element dynamically in Angular, there are a few different ways to do it.

Method 1: ngClass directive

The ngClass directive allows you to add and remove CSS classes based on conditions. You can use it like this:

<div [ngClass]="{'my-class': shouldAddClass}">Hello World</div>

In this example, the "my-class" class will be added to the div element if the "shouldAddClass" variable is true.

Method 2: Renderer2.addClass()

If you need to add a class to an element in TypeScript code, you can use the Renderer2 class that is provided by Angular. Here's an example:

import { Component, ElementRef, Renderer2 } from '@angular/core';

  selector: 'app-root',
  template: '<div #myDiv>Hello World</div>'
export class AppComponent {
  constructor(private elementRef: ElementRef, private renderer: Renderer2) {}

  ngAfterViewInit() {
    const div = this.elementRef.nativeElement.querySelector('#myDiv');
    this.renderer.addClass(div, 'my-class');

In this example, we inject the ElementRef and Renderer2 services into our component's constructor. Then, in the ngAfterViewInit method (which is called after the view has been initialized), we use the Renderer2.addClass method to add the "my-class" class to the div element.

Method 3: HostBinding decorator

If you need to add a class to the host element of a component, you can use the HostBinding decorator. Here's an example:

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

  selector: 'app-root',
  template: 'Hello World'
export class AppComponent {
  @HostBinding('') shouldAddClass = true;

In this example, we use the HostBinding decorator to bind the "shouldAddClass" property to the "" attribute of the host element (which is the app-root element in this case). When the "shouldAddClass" property is true, the "my-class" class will be added to the host element.


These are three different ways to add a class to an element dynamically in Angular. Choose the one that fits your use case the best!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]