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?
Use it like [class.className]="condition" to add className if condition is true. In this scenario className is hardcoded in template.
If you want your class name to be dynamic you can use this syntax: class="class1 class2 {{className}}".
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: class="class1 class2 itemOneFromList itemTwoFromList ..."
I provided a stackblitz
Why not to use Angular ngClass directive with property binding to add classes dynamically?
<div [ngClass]="propertyVariable"></div>