With the NgStyle directive, you can set a given DOM element CSS properties from Angular expressions. The simplest way to use this directive is by doing [style.]=”value”. For example:
<div [style.background-color]="'yellow'"> Uses fixed yellow background </div>
This snippet is using the NgStyle directive to set the background-color CSS property to the literal string ‘yellow’. Another way to set fixed values is by using the NgStyle attribute and using key-value pairs for each property you want to set, like this:
<div [ngStyle]="{color:'red','background-color':'black'}">
This is ng Style example
</div>
Note: Notice that in the ng-style specification we have single quotes around background-color but not around color. Why is that? Well, the argument to ng-style is a Javascript object and color is a valid key, without quotes. With background-color, however, the dash character isn’t allowed in an object key, unless it’s a string so we have to quote it. Generally, I’d leave out quoting as much as possible in object keys and only quote keys when we have to.
Example :
Step1: Create new component and add following code
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-styleex',
templateUrl: './styleex.component.html',
styleUrls: ['./styleex.component.css']
})
export class StyleexComponent implements OnInit {
mycolor: string;
mybackgroundcolor: string;
constructor() {
this.mycolor ='blue';
this.mybackgroundcolor ='red';
}
ngOnInit() {
}
change(val1, val2)
{
this.mycolor =val1;
this.mybackgroundcolor =val2;
}
method()
{
return { color: 'yellow' , 'background-color':'orange' };
}
}
Step2: Add following code into html
<p>
styleex works!
</p>
<div [style.background-color]="'yellow'">
Uses fixed yellow background
</div>
<!-- <div [ngStyle]="{color:'red','background-color':'black'}">
This is ng Style example
</div> -->
<div [ngStyle]="{color : mycolor , 'background-color':mybackgroundcolor}">
This is Dynamic Div
</div>
<!-- Use ngStyle using method Start -->
<div [ngStyle]="method()">this div style are generated using method</div>
<!-- Use ngStyle using method End -->
<div>
Font Color: <input type="text" #txt1 /> <br/>
background Color <input type="text" #txt2 /> <br/>
<button (click)="change(txt1.value, txt2.value)">Change Style</button>
</div>
Step3: Add reference of newly generated component and run program.
Output
