In this TuTo, we will answer about these questions :
- When and how to use the NgStyle directive to set an elements style ?
- When and how to use the NgClass directive to set an elements classes?
NgStyle
The NgStyle directive lets you set a given DOM elements style properties.
<div [ngStyle]="{'background-color':'green'}"></<div>
in the first example , we try to set the background color of the div to green. But, ngStyle becomes much more useful when the value is dynamic.
<div [ngStyle]="{'background-color':person.country === 'TN' ? 'orange' : 'red' }">
</<div>
In the second example , we uses the ternary operator to set the background color to orange if the persons country is the TN else red. Also we can add a function to set the color , for that, lets see the next example :
@Component({
selector: 'ngstyle-example',
template: `<h4>NgStyle</h4>
<ul *ngFor="let person of people">
<li [ngStyle]="{'color':getColor(person.country)}"> {{ person.name }} ({{ person.country }}) (1)
</li>
</ul>
`
})
class NgStyleExampleComponent {
getColor(country) { (2)
switch (country) {
case 'UK':
return 'green';
case 'USA':
return 'blue';
case 'HK':
return 'red';
}
}
people: any[] = [
{
"name": "Douglas Pace",
"country": 'UK'
},
{
"name": "Mcleod Mueller",
"country": 'USA'
},
{
"name": "Day Meyers",
"country": 'HK'
},
{
"name": "Aguirre Ellis",
"country": 'UK'
},
{
"name": "Cook Tyson",
"country": 'USA'
}
];
}
NgClass
The NgClass directive allows you to set the CSS class dynamically for a DOM element.
The NgClass directive is very similar to ngClass used to do in Angular 1.
We can use the NgClass in two ways:
- By passing an object literal to the directive [EXP1]
- The value can also be an expression [EXP1]
Example 1:
[ngClass]="{'text-success':true}"
Example 2:
<h4>NgClass</h4>
<ul *ngFor="let person of people">
<li [ngClass]="{
'text-success':person.country === 'UK',
'text-primary':person.country === 'USA',
'text-danger':person.country === 'HK'
}">{{ person.name }} ({{ person.country }})
</li>
</ul>