NgStyle vs Style Binding in Angular

We can bind inline style to any element using style binding.

Style Binding

To add a single style dynamically from any element we can make use of style binding. Syntax is

[style.style_property] = "expression"

The value of the expression is normally a string.

<div [style.color]="hasError ? 'red' : 'black'">
...
</div>
<div [style.background-color]="'yellow'">
...
</div>

With style binding we can set only a single style however, to set multiple styles we can use ngStyle directive.

The ngStyle Directive

To add multiple styles, we can pass an object where keys will be the CSS property names and the values will be respective expressions.

<div [ngStyle]="{width:'10px', height: '20px'}">
...
</div>

We can also define the object in the component and use it in the template.

styles = {
  'color': this.hasError ? 'red' : 'black',
  'border-left': this.hasError ? '3px solid red' : '',
  'background-color': this.isActive ? 'green' : 'white',
  'width': this.boxWidth + 'px',
  'height': this.boxHeight + 'px',
  'font-size': this.textFont + 'px'
}
<div [ngStyle]="styles">
... 
</div>

Now you are all set to add or remove styles to your HTML elements dynamically with whichever binding is appropriate for you.

Related

NgClass vs class binding in Angular

Leave a Reply

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