Style binding in Angular

We can set the inline styles of a HTML element using the style binding in angular. The syntax resembles the syntax of the property binding. You can add styles conditionally to an element, hence creating a dynamically styled element.

Further Reading on Angular Styles

Syntax

The syntax of the style binding is similar to the property binding.

The Style Binding uses the [] brackets. Place the CSS Style property (binding target) inside the square bracket. The CSS Style property must begin with ‘Style’ followed by a dot (.) and then style name.

For Example, to set the color of p element.

Style binding Example

Setting the background color of a paragraph

Setting the border style of a button.

Conditionally setting the styles

Define a variable status in the component

And use that variable in the template to set the color of button either to red and blue depending on the value of the status variable.

Another way is to create the getColor() method and use it in the template as shown below.

Setting the units

The styles like font-size, width etc have unit extension. The following example conditionally sets the font-size in “px” unit

The style property name can be written in either dash-case (font-size), as shown in above example, or camelCase (fontSize) as shown below.

Setting Multiple styles

To change the multiple styles, we need to add each one separately as shown below.

The style binding is the easy way to set a single style of a HTML element. Although you can use it to set several inline styles as shown in the above example, the better way is to use the ngStyle directive.

Summary

The style binding is one of the several ways you can use styles in angular. You can refer to the following tutorials.

1 thought on “Style binding in Angular”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top