Angular provides special support in property bindings for assigning the host element to classes and for configuring individual style properties. I describe these bindings in the sections that follow, along with details of the ngClass and ngStyle directives, which provide closely related features.
There are three different ways in which you can use data bindings to set style properties of the host element: the standard property binding, the special style binding, and the ngStyle directive. All three are described in the following table and demonstrated in the sections that follow.
Example | Description |
---|---|
<div [style.myStyle]="expr"> | This is the standard property binding, which is used to set a single style property to the result of the expression. |
<div [style.myStyle.units]="expr"> | This is the special style binding, which allows the units for the style value to be specified as part of the target. |
<div [ngStyle]="map"> | This binding sets multiple style properties using the data in a map object. |
Setting a Single Style Property
The standard property binding and the special style bindings are used to set the value of a single style property. The difference between these bindings is that the standard property binding must include the units required for the style, while the special binding allows for the units to be included in the binding target.To demonstrate the difference, The following example adds two new properties to the component.
NgStyle Example
import { Component } from "@angular/core";
import { Model } from "./repository.model";
@Component({
selector: "app",
templateUrl: "template.html"
})
export class ProductComponent {
model: Model = new Model();
getClasses(key: number): string {
let product = this.model.getProduct(key);
return "p-2 " + (product.price < 50 ? "bg-info" : "bg-warning");
}
getClassMap(key: number): Object {
let product = this.model.getProduct(key);
return {
"text-center bg-danger": product.name == "Kayak",
"bg-info": product.price < 50
};
}
fontSizeWithUnits: string = "30px";
fontSizeWithoutUnits: string= "30";
}
Read More
Comments
Post a Comment