Angular ngStyle Directive

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.

ngStyle Syntax

Where

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.

The units (for example px, em) are prefixed to the styleName.

ngStyle Example

Change Style Dynamically

Initialize a variable color and add it to your component

And in your template, add the following

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.

ngStyle multiple attributes

We can change multiple style as shown in the following example

The JavaScript object is assigned to the ngStyledirective 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.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

Specifying CSS Units in ngStyle

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.

Using object from Controller

Create a class as shown below

And in controller initialize the class

Then you can refer it in your template as shown below

Change Style using Style Property Binding

We can also change the Styles using the Style Binding. .

Further Reading on Angular Styles

You can download the source code from GitHub

Leave a Comment

Your email address will not be published.

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

Scroll to Top