Angular: ngClass and it’s usage to change CSS dynamically
1 min readOct 13, 2020
What is ngClass
The ngClass
directive takes an expression that will be used to determine which state styles to apply at a given time to the styled element.
Using ngClass
The expression passed on to ngClass
can be:
- an object
<button [ngClass]=”{ btn:true, ‘btn-primary’:false}”>will become <button class="btn">
- an array
<button [ngClass]=”[‘btn’, ‘btn-primary’]”>Button</button>will become <button class="btn btn-primary">
- a string
<button [ngClass]=”’btn btn-primary’”>
Lets look at a more complete example using the object expression
/** parentComponent.component.ts **/
calculateClasses(){
return {
btn: condition ? true: false,
‘btn-primary’: true,
‘btn-extra-class’: this.someBooleanVariable
};
}/** parentComponent.component.html**/
<button [ngClass]="calculateClasses()"