NgStyle vs Style Binding in Angular
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
The ngStyle
directive accepts an object where keys will be the CSS property names and the values will be respective expressions.
<div [ngStyle]="{width:'10px', height: '20px'}">
...
</div><div [ngStyle]="{color: isPassed?'green':'red',
backgroundColor: getColor()}">
...
</div>
We can also define the style object in the component and use it in template. We will set the CSS property values with dynamic validations.
Component (.ts file)
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'
}
HTML
<div [ngStyle]="styles">
...
</div>
Now you are all set to add or remove styles to your HTML elements dynamically with whichever binding appropriate for you.
Thanks for your time☺️
For more Web development blogs, Please visit jscurious.com