We can set the inline styles of a HTML element using the style binding in angular. The syntax resembles the syntax of the property binding. You can add styles conditionally to an element, hence creating a dynamically styled element.
Further Reading on Angular Styles
- Angular ngStyle Directive
- class bindng
- ngClass Directive
- Angular Global Styles
- Angular Component Styles
- View Encapsulation in Angular
Table of Contents
Syntax
The syntax of the style binding is similar to the property binding.
1 2 3 | [style.style-property] = "style-value" |
The Style Binding uses the []
brackets. Place the CSS Style property (binding target) inside the square bracket. The CSS Style property must begin with ‘Style’ followed by a dot (.) and then style name.
For Example, to set the color of p
element.
1 2 3 | <p [style.color]="'red'">Give me red</p> |
Style binding Example
Setting the background color of a paragraph
1 2 3 | <p [style.background-color]="'grey'">some paragraph with grey background</p> |
Setting the border style of a button.
1 2 3 | <button [style.border]="'5px solid yellow'">Save</button> |
Conditionally setting the styles
Define a variable status in the component
1 2 3 | status:string='error'; |
And use that variable in the template to set the color
of button either to red and blue depending on the value of the status
variable.
1 2 3 | <button [style.color]="status=='error' ? 'red': 'blue'">Button 1</button> |
Another way is to create the getColor()
method and use it in the template as shown below.
1 2 3 4 5 | getColor() { return 'yellow'; } |
1 2 3 | <button [style.color]="getColor()">Button 2</button> |
Setting the units
The styles like font-size
, width
etc have unit extension. The following example conditionally sets the font-size
in “px”
unit
1 2 3 | <button [style.font-size.px]="'20'" >Big Button</button> |
The style property name can be written in either dash-case (font-size), as shown in above example, or camelCase (fontSize) as shown below.
1 2 3 | <button [style.fontSize.px]="'20'" >Big Button</button> |
Setting Multiple styles
To change the multiple styles, we need to add each one separately as shown below.
1 2 3 4 5 6 7 | <p [style.color]="getColor()" [style.font-size.px]="'20'" [style.background-color]="status=='error' ? 'red': 'blue'"> paragraph with multiple styles </p> |
The style binding is the easy way to set a single style of a HTML element. Although you can use it to set several inline styles as shown in the above example, the better way is to use the ngStyle directive.
Summary
The style binding is one of the several ways you can use styles in angular. You can refer to the following tutorials.
Very good, there are many ways of styling in angular.