[class.] binding
You can add and remove CSS class names from an element's class
attribute with a class binding.
Class binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix class
, optionally followed by a dot (.
) and the name of a CSS class: [class.class-name]
.
You can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding:
Source
<div class="bold italic red"
[class]="textClass">
Demo text
</div>
export class AppComponent {
textClass = 'bold italic';
}
.bold {
font-weight: 600;
}
.italic {
font-style: italic;
}
Result
Demo text
Finally, you can bind to a specific class name. Angular adds the class when the template expression evaluates to truthy. It removes the class when the expression is falsy.
Source
<div [class.special]="isSpecial">
The class binding is special
</div>
<div class="special"
[class.special]="!isSpecial">
This one is not so special
</div>
export class AppComponent {
isSpecial = true;
}
.special {
background: #36cadb;
color: #ffffff;
}
Result
The class binding is special
This one is not so special
While this is a fine way to toggle a single class name, the NgClass directive is usually preferred when managing multiple class names at the same time.