How to add class to Angular component


angular css

In this post we will discover 5 ways to add class to Angular component

Inline Style

This is basic option for any Web-framework:

<div class="some-class">Some text</div>

@Component decorator

If you want to apply a class to the entire component, you can use the styleUrls or styles property in the @Component decorator.

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

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'] // Here you define your CSS file
})
export class YourComponent {
}

In your CSS file (your-component.component.css):

:host {
  display: block;
  /* Add styles here */
}

Class binding

You can use the following combination on every component [class.classname]="condition":

<div [class.active]="isActive">Content here</div>

ngClass directive

You can use conditions directly in template for multiple classes using ngClass directive:

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

Or you can write conditions in component and use an object property in the template:

export class YourComponent {
  classes = {
    'class1': true,
    'class2': false
  };
}
<div [ngClass]="classes">Content here</div>

Renderer2 service

Using Renderer2 service you can add CSS class to the host element of the component:

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

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'],
})
export class YourComponent {
  private renderer = inject(Renderer2);
  private el = inject(ElementRef);

  ngOnInit() {
    // It will apply class to the host element
    this.renderer.addClass(this.el.nativeElement, 'your-class-name');
  }
}
comments powered by Disqus