37
loading...
This website collects cookies to deliver better user experience
ngStyle
directive.[ngStyle]="{<Valid_Style>}"
e.g. 'background-color':'green'
<div [ngStyle] = "{ background: 'green' }" >
This text will have a background green...
</div>
ngStyle
is an attribute directive we are enclosing it inside a square bracket [] (as explained in my last post. Then comes the equals operator =
followed by an object inside double quotes "
or single quotes '
(both will work).background
is the property name and its corresponding value green.div
on which ngStyle
is used is getting a background of green color.ngStyle
[ngStyle]="{'< CSS STYLE PROPERTY >': < CONDITION > }"
<div
[ngStyle]="{ 'background-color':
serverOneStatus === 'up' ? 'green' : 'red' }">
SERVER 1
</div>
serverOneStatus
we created in our previous post. Remember???serverOneStatus
value to anything except up it will give the following output -serverOneStatus === 'up'
is evaluating to true
the background is green and if it is false background is red.[ngStyle]="<function()>"
getStyle() {
return {
'font-size': '20px',
'color': 'gray',
'background': 'lightgreen'
};
}
export class AttributeDirectiveDemoComponent implements OnInit {
serverOneStatus = 'up1';
ngOnInit(): void { }
getStyle() {
return {
'font-size': '20px',
'color': 'gray',
'background': 'lightgreen'
};
}
}
<div [ngStyle]="getStyle()">SERVER 1</div>
getStyle
and we are calling the function from the template in the following way [ngStyle]="getStyle()"
ngStyle
.