In this tutorial we will discuss Angular Style Binding. Before starring this article please go through our previous article Angular Class Binding. In this article we will cover below point
- What is Angular Style Binding ?
- Style Binding with Examples.
➤ What is Angular Style Binding ?
The Angular Style Binding is basically used to set the style in HTML elements. You can use both inline as well as Style Binding to set the style in the element in Angular Applications. Setting inline styles with style binding is very similar to setting CSS classes with class binding.
When we run the application, you can see the button color is applied as expected.
Fig-1 |
➥ Let's take another example where we set the style (font-weight). If the property "IsBold" (this Boolean property is defined in the AppComponent class) is true, then the font-weight style is set to bold else it is set to normal.
When we run the application, you can see the button color and button font weight is applied as expected.
Fig-2 |
➥ Multiple Inline Styles in Angular Application
If you want to set multiple inline styles in the angular application, then you need to use NgStyle directive as shown in the below example.
Code Snippet Explanation
- The ngStyle is bounded to myCustomCSS() method of the AppComponent class.
- The myCustomCSS() method returns an object with 3 key/value pairs. The key is a style name, and the value is a value for the respective style property or an expression that returns the style value.
- The let is a new type of variable declaration in JavaScript. Instead of let you can also use var here.
When we run the application, you can see the custom class CSS is applied.
Fig-3 |
Summary
Post a Comment