Home > Enterprise >  How can I dynamically set a CSS class list of an element in Angular from the class component?
How can I dynamically set a CSS class list of an element in Angular from the class component?

Time:12-27

I want to set a property as a string and add that dynamically into a certain DOM element as a class list value.

<div [className]="propertyVariable"></div>

And inside the class component:

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

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.css'],
})
export class OrderComponent implements OnInit {
  propertyVariable: string;

  constructor() {}

  changePropertyVariable() {
    this.propertyVariable = 'class1 class2';
  }

  ngOnInit(): void {}
}

So far it does not add the class list am setting to that variable. How do I properly bind to that property?

CodePudding user response:

Use it like [class.className]="condition" to add className if condition is true. In this scenario className is hardcoded in template.

And if you want your class name to be dynamic you can use this syntax: .

For appending a list of classes you can use it like above only pass className = classList.join(' '); as the className.

So your template will be like:

CodePudding user response:

Why not to use Angular ngClass directive with property binding to add classes?

<div [ngClass]="propertyVariable"></div>

https://angular.io/guide/property-binding

  • Related