Angular Tutorials: Angular ngStyle Directive

In this Angular Tutorial, we will learn about the ngstyle directive, why we need it, and the different ways of using angular style binding.

Inline styles are the most used way to apply small styles to elements.

For example:

//For coloring a div
<div style="background:#333"></div>

Now, to apply styles in angular, we can use input functions and pass style to it:

//For coloring a div
<div [style.background]="bgColor"></div>
// in ts file
public bgColor:string = '#333';

Suppose we want to apply one more style to it for our text color:

//For coloring a div
<div [style.background]="bgColor"
[style.color]="txtColor"
></div>
// in ts file
public bgColor:string = '#333';
public txtColor:string = '#fff';

Now the problem with this approach is you have to rewrite [style.[styleName]] multiples times for all the styles which you want to apply to. So to solve that problem, we have ngStyle Directive.

ngStyle Directive expects the value as a configuration object, with each property as a key/value pair. Let’s take a look at the code:

//For coloring a div
<div [ngStyle]="{'background-color':bgColor,'color':txtColor}"
></div>
// in ts file
public bgColor:string = '#333';
public txtColor:string = '#fff';

As expected, our code looks much cleaner and readable. But it gets better — you can even use angular style binding conditionally.

Suppose you have a boolean property and based on that property, you want to change the background color of the div:

//For coloring a div
<div [ngStyle]="{'background-color': condition?bgColordark:bgColorlight,'color':txtColor}"
></div>
// in ts file
public bgColordark:string = '#333';
public bgColorlight:string = 'yellow';
public condition:boolean= true;
public txtColor:string = '#fff';

Just like the case of angularngClass, if our ngStyle expression starts to get too large, we can always call a component method to get the configuration object:

<div [ngStyle]="GetStyles()"
></div>
//in ts 
public bgColordark:string = '#333';
public bgColorlight:string = 'yellow';
public condition:boolean= true;
public txtColor:string = '#fff';
public GetStyles:any{
return {'background-color': this.condition? this.bgColordark:this.bgColorlight,
'color':this.txtColor};
}

Thanks a lot. For more of this kind of angular tutorials and articles visit Smartcodehub.