Angular dynamic CSS
There are basically 2-3 ways you can bind css class to angular components.
You provide a class name with class.className
between brackets in your templates and then an expression on the right that should evaluate to true or false to determine if the class should be applied. That is the below one where extra-sparkle(key) is the css class and isDelightful(value)
.
<div [class.extra-sparkle]="isDelightful">
When multiple classes should potentially be added, the NgClass directive comes in really handy. NgClass
should receive an object with class names as keys and expressions that evaluate to true or false. extra-sparkle is the key and isDelightful
is the value (boolean
).
<div [ngClass]="{'extra-sparkle': isDelightful}">
Now along with extra sparkle, you can glitter your div
also.
<div [ngClass]="{'extra-sparkle': isDelightful,'extra-glitter':isGlitter}">
or
export class AppComponent {
isDelightful: boolean = true;
isGlitter: boolean = true;
get sparkleGlitter()
{
let classes = {
extra-sparkle: this.isDelightful,
extra-glitter: this.isGlitter
};
return classes;
}
}<div [ngClass]='sparkleGlitter'>
For ngClass
, you can have conditional ternary operators too.
8
In [ngClass]
you can add one of two different classes like this:
<div [ngClass]="a === b ? 'class1' : 'class2'">
In the current version of Angular following syntax is also working fine:
[class]="{toggled: sidebarActive, test: true,test1: sidebarActive}