NgStyle

The NgStyle directive is used for setting an element's style properties. Let's rework our previous CarHorsepowerComponent example, which used to demonstrate NgSwitch, NgCase, and NgDefault, in order to show how the same desired outcome (that is, conditionally styling elements) can be better done using NgStyle:

@Component({
selector: 'car-hp',
template: `
<h3>Cars styled by their HP range</h3>
<ul *ngFor="let car of cars">
<li [ngStyle]="{ getCarTextStyle(car.horsepower) }" >
{{ car.make }} {{ car.model }}
</li>
</ul>
`,
encapsulation: ViewEncapsulation.Native
})
class CarHorsepowerComponent {
getCarTextStyle(horsepower) {
switch (horsepower) {
case (horsepower >= 375):
return 'color:#fff; background-color:#ff0000;';
case (horsepower >= 200 && horsepower < 375):
return 'color:#000; background-color:#ffa500;';
default:
return 'color:#000; background-color:#ffff00;';
}
}
cars: any[] = [
{
"make": "Ferrari",
"model": "Testerosa",
"horsepower": 390
},
{
"make": "Buick",
"model": "Regal",
"horsepower": 182
},
{
"make": "Porsche",
"model": "Boxter",
"horsepower": 320
},
{
"make": "Lamborghini",
"model": "Diablo",
"horsepower": 485
}
];
}

In our reworking of the original CarHorsepowerComponent class, we've lightened up our component template by moving the logic into a function within the class. We've removed the styles property of the component annotation, and instead created a function (that is, getCarTextStyle) to return the style text to the calling function so that we can set the correct style.

Though this is a cleaner approach, we can do even better. Since we're setting a style for the car text, we can just change the style class altogether, as opposed to passing the actual style rulesets via text.

In the next section, on NgClass, we'll rework our code one more time to see how this is done. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.199.138