Angular 10 Tutorial - Class Binding
In this tutorial, we will learn about class binding in Angular 10. Class binding is used to set a class property of a view element. We can add and remove the CSS class name from an element's class attribute with class binding.
Using Class Binding in Angular 10
Alright, so let's see how we can use class binding in Angular 10. Switch to the project and open the app.component.css file and create some CSS classes:
.success{
color:green;
}
.error{
color:red;
}
.special{
font-weight: 700;
text-decoration: underline;
}
Now, let's bind these classes. Before binding these classes, let's create some properties. Go to the app.component.ts file and create some properties:
success='success';
error = 'error';
special='special';
Now, go to the app.component.html file and write the following code:
<p [class]="success">Success Message Here…</p>
<p [class]="error">Error Message Here…</p>
<p [class]="special">Special Message Here…</p>
Alright, now let's check it. Switch to the browser and you can see here the class has been applied on these text.
Conditional Class Binding
Now, let's see the conditional class binding. For that, let's create one new property:
hasError=false;
Now, go to the app.component.ts file and add one more paragraph:
<p [class.error]="hasError">Conditonal Message Here. .</p>
If the hasError value is true, then this error class will be applied on this p tag, otherwise, it will not be applied. So, this time hasError value is false. So, let's check it in the browser and you can see the text in normal color. If I change it into true, you can see the text is now becomes in red in color. Ok, it means the error class has been applied here.
Multiple Classes Binding
Now, let's see the multiple classes binding. For that, just go to the app.component.ts file and create a property:
multiClasses = ["success","special"];
Now, let's bind this. Go to the app.component.ts file:
<p [class] = "multiClasses">Multiple Class Binding</p>
Now, let's check it. And here you can see that both the success and special classes are applied.
Conditional Applied Multiple Class Binding
Now, let's see the conditional applied multiple class binding. For that, just create one new property into the app.component.ts file:
conditionalMultiClasses={
"success":!this.hasError,
"error":this.hasError.
};
Now, let's bind it. So, go to the app.component.html file and create a new paragraph:
<p [class] = "conditionalMultiClasses">Conditional Multiple Class Binding</p>
Now, let's check it. This time, the hasError value is false. Now, switch to the browser and you can see the color. If I change it into true, then it becomes into red in color. So, in this way, you can do class binding in Angular 10.