Style Binding In Angular

Style Binding In Angular

In angular, we may use style binding to set the inline styles of an HTML element. The syntax is similar to that of property binding. You can conditionally apply styles to an element, resulting in a dynamically styled element.

Syntax

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

[style.style-property] = "style-value"

The [] brackets are used in the Style Binding. Inside the square bracket, put the CSS Style property (binding target). The 'Style' property in CSS must be preceded by a dot (.) and then the style name.

To set the color of the p element, for example.

<p [style.color]="'red'">Give me red</p>

Style binding Example

Changing the color of a paragraph's backdrop

<p [style.background-color]="'grey'">some paragraph with grey background</p>

Changing a button's border style.

<button [style.border]="'5px solid yellow'">Save</button>

Conditionally setting the styles

In the component, define a variable status.

status:string='error';

And, depending on the value of the status variable, use that variable in the template to change the color of the button to red or blue.

<button [style.color]="status=='error' ? 'red': 'blue'">Button 1</button> 

Another option is to construct the getColor() method and use it in the template like in the example below.

getColor() {
  return 'yellow';
}

<button [style.color]="getColor()">Button 2</button> 

Setting the units

The font size, width, and other styles have a unit extension. The font size in the "px" unit is conditionally set in the following example.

<button [style.font-size.px]="'20'" >Big Button</button>

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

<button [style.fontSize.px]="'20'" >Big Button</button>

Setting Multiple styles

We must add each style independently to alter the numerous styles, as demonstrated below.

<p [style.color]="getColor()" 
   [style.font-size.px]="'20'"      
   [style.background-color]="status=='error' ? 'red': 'blue'">
   paragraph with multiple styles
</p>

Style binding is a simple method of assigning a single style to an HTML element. Although you can use it to set several inline styles as demonstrated in the previous example, the ngStyle directive is a superior option.

Conclusion

In Angular, you may use styles in a variety of ways, including style binding.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post