Angular 10 Tutorial - Style Binding
In this tutorial, we will learn about style binding in Angular 10. Style binding is used to set a style of a view element. We can set inline styles with style binding.
Using Style Binding in Angular 10
Now, let's see how we can do style binding in Angular 10. So, switch to the project and open the app.component.html file. Now, just add a paragraph:
<p>Style Binding….</p>
Now, here for binding the CSS:
<p [style.color]="'blue'">Style Binding….</p>
Now, save the file and let's check it. So, switch to the browser and... Here you can see the text color is blue. If I change the color to green, now the text color is green.
Style Binding through Property
Now, let's see the style binding through property. For that, just create a property inside the app.component.ts file:
textColor='Blue';
Now, go to the app.component.html file and here just add another paragraph and bind the style:
<p [style.color]="textColor" >Style Binding using Property…</p>
Now, let's check. So, switch to the browser and here you can see the text color is blue.
Multiple Style Property Binding
Alright, now let's see multiple style property binding. For that, create a new property inside the app.component.ts file:
textStyle={
color:"blue";
fontStyle:"italic";
textDecoration:"underline";
}
Here, you can't use hyphen. You have to use camel case. Alright, now let's bind it. So, inside the app.component.html file, add a new paragraph and bind the style:
<p [style]="textStyle">Multiple style binding….</p>
Now, let's check it. You can see the text in blue color, italic, and underline.
Conditional Style Binding
Now, let's see the conditional style binding. For that, create a new property:
hasError = false;
Now, go to the app.component.html file and here add a new paragraph tag:
<p [style.color] = "hasError ? 'red' : 'green'">Conditonal style binding…</p>
If the hasError value is true, then the red color will be applied here, otherwise, green. So, let's check. You can see the color is green. Now, let's change the hasError value to true. Now, you can see the color is red. So, in this way, you can do style binding in Angular 10.