[style.] binding
This is the documentation for Angular 8.
You can switch to the latest version Angular 10.
You can switch to the latest version Angular 10.
You can set inline styles with a style binding.
Style binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix style
, followed by a dot (.
) and the name of a CSS style property: [style.style-property]
.
Source
<button [style.color]="isSpecial ? 'red': 'green'">Red</button>
<button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>
export class AppComponent {
isSpecial = true;
canSave = false;
}
Result
Some style binding styles have a unit extension. The following example conditionally sets the font size in “em” and “%” units .
Source
<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button>
<button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>
export class AppComponent {
isSpecial = true;
}
Result
Note that a style property name can be written in either dash-case, as shown above, or camelCase, such as fontSize
.
While this is a fine way to set a single style, the NgStyle directive is generally preferred when setting several inline styles at the same time.