The Angular ngStyle directive allows us to set the many inline style of a HTML element using an expression. The expression can be evaluated at run time allowing us to dynamically change the style of our HTML element. In this tutorial, we learn how to use the ngStyle with an example.
<element [ngStyle]="{'styleNames': styleExp}">...</element>
element is the DOM element to which style is being applied
styleNames are style names ( ex: ‘font-size’, ‘color’ etc). with an optional suffix (ex: ‘top.px’, ‘font-style.em’),
styleExp is the expression, which is evaluated and assigned to the styleNames
We can add more than one key value pairs 'styleNames': styleExp each separated by comma.
In the following example,some-element gets the style of font-size of 20px.
<some-element [ngStyle]="{'font-size': '20px'}">Set Font size to 20px</some-element>
The units (for example px, em) are prefixed to the styleName.
Syntax:
<element [ngStyle]="{'styleName.unit': widthExp}">...</element>
Example:
<some-element[ngStyle]="{'font-size.em': '3'}">...</some-element>
Initialize a variable color and add it to your component
color: string= 'red';
And in your template, add the following
<input [(ngModel)]="color" />
<div [ngStyle]="{'color': color}">Change my color</div>
In the above example, we apply ngStyle directive to the div element. We assign JavaScript object {'color': color} to the ngStyledirective. The variable color is dynamically changed by the user input and it is applied instantly to the div element
The following code uses the ternary operator to set the background color to red if the status variables indicator is set to “error” else blue.
div [ngStyle]="{'background-color':status === 'error' ? 'red' : 'blue' }"></<div>
We can change multiple style as shown in the following example
<p [ngStyle]="{'color': 'purple',
'font-size': '20px',
'font-weight': 'bold'}">
Multiple styles
</p>
The JavaScript object is assigned to the ngStyle directive containing multiple properties. Each property name of the object acts as a class name. The value of the property is the value of the style.
CSS has several units for expressing a length, size etc. The units can be em, ex, %, px, cm, mm, in, pt, PC etc. We prefix the units to the StyleName as shown below.
<input [(ngModel)]="size" />
<div [ngStyle]="{'font-size.px': size}">Change my size</div>
Create a class as shown below
class StyleClass {
'color': string= 'blue';
'font-size.px': number= 20;
'font-weight': string= 'bold';
}
And in controller initialize the class
styleClass: StyleClass = new StyleClass();
Then you can refer it in your template as shown below
<div [ngStyle]="styleClass">size & Color</div>
We can also change the Styles using the Style Binding.
Further Reading on Angular Styles
You can download the source code from GitHub