Mass Binding of CSS Classes in Angular
The ngClass
directive allows you to enable or disable a set of CSS classes in a tag at once. The directive takes an object as its value, the keys of which are classes, and the values are Boolean values. The class will be enabled if it is set to true
, and disabled if false
.
Let's look at it in practice. Let's say we have the following classes:
.blue {
color: blue;
}
.bold {
font-weight: bold;
}
Let's look at examples of how to enable and disable these classes for a block.
Example
Let's turn on one class and turn off the other:
<div [ngClass]="{blue: true, bold: false}">
text
</div>
Example
Let the states of classes be stored in class properties:
export class AppComponent {
public isBlue: boolean = true;
public isBold: boolean = false;
}
Let's bind the visibility of the class depending on the values of our properties:
<div [ngClass]="{blue: isBlue, bold: isBold}">
text
</div>
Example
The property can be a whole object with classes and states:
export class AppComponent {
public styles = {
blue: false,
bold: true,
}
}
Let's bind this object to our block:
<div [ngClass]="styles">
text
</div>
Example
We can get values for our object from other properties of the class:
export class AppComponent {
public isBlue: boolean = false;
public isBold: boolean = true;
public styles = {
blue: this.isBlue,
bold: this.isBold,
}
}
Let's bind this object to our block:
<div [ngClass]="styles">
text
</div>
Practical tasks
Create two CSS classes. Let one of them define the background of the block, and the second one - the font size.
Make two buttons. Let pressing the first button toggle the first class, and pressing the second toggle the second class.