Angular Style Binding and NgStyle

By Arvind Rai, March 28, 2024
On this page we will learn style binding using style and NgStyle in Angular application.
1. We can perform style binding in two-ways.
a. Use the prefix style followed by a dot and the name of the CSS style.
b. Use NgStyle directive.

2. Style binding can have single style binding and multiple style binding. We can also bind styles with units.
3. In styling precedence, template binding is at highest precedence, then directive host binding and then component host binding.
4. Style binding binds an inline style property with a given value. It is used in the same way as property binding.
5. NgStyle sets one or more than one inline styles dynamically.
6. NgStyle and style property binding both can be used with bracket [] and bind- keyword.
7. Find the syntax for single style binding.
<html_element [style.style_property] = "'style_value'"> 
With unit
<html_element [style.style_property.unit] = "'style_value'"> 
For multi-style binding.
<html_element [style] = "style_expression"> 
Using NgStyle directive.
<html_element [ngStyle] = "style_expression"> 

1. Style Binding with style

Using style binding we set inline styles. The syntax is same as we use in property binding with the difference that style binding starts with style. . Find the syntax for style binding.

[style.style-property] = "style-value"

Here style is a prefix and style-property is a name of a CSS style property. style prefix and style property are concatenated using dot (.) .
Style property binding can be achieved with bracket [], bind- keyword and interpolation {{}}.
Find the code to use style binding.
<p [style.color] = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p bind-style.color = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p style.color = "{{result > 30 ? 'blue' : 'green'}}"> Hello Color World! </p>  
In the above example, we are using conditional operator. When the condition result > 30 returns true then color style will be set to blue otherwise green. Let us know about conditional operator.

Conditional (ternary) Operator
Conditional operator that is also called ternary operator, is used as a short cut of if else statement. Find the syntax.
condition ? expr1 : expr2
When the condition is true then expr1 will be returned otherwise expr2 will be returned.

2. Single Style Binding

To bind a single style, we need to use the format [style.<style_name>]
1. Add color.
<div [style.color]="'red'">
 ------
</div>
<div [style.color]="'#FF5733'">
 ------
</div> 
2. Add background color.
<p [style.background-color]="'brown'">
  ------
</p>
<p [style.background-color]="'#74992e'">
  ------
</p>
<p [style.background-color]="'rgb(255, 255, 128)'">
   ------
</p> 
3. Background from URL.
<p [style.background]="'no-repeat url(\'/assets/images/green.gif\')'">
  ------
</p> 
4. Getting value from Variable
TS:
color= "#ff0099";
width= "150px";
height= "140px"; 
HTML:
<div [style.color]="color">
  ------
</div>
<div [style.width]="width">
  ------
</div>
<div [style.height]="height">
  ------
</div> 


3. With Units

In single style binding, unit can be assigned in two ways. Assign unit with value or assign unit with style keyword.
1. With in px
<div [style.width]="'200px'">
  ------
</div>
<div [style.width.px]="'200'">
  ------
</div> 
We see that we can use unit in two ways either [style.width]="'200px'" or [style.width.px]="'200'".
2. Height in em
<div [style.height]="'20em'">
  ------
</div>
<div [style.height.em]="'20'">
  ------
</div> 
3. Font size in px
<div [style.font-size]="'10px'">
  ------
</div>
<div [style.font-size.px]="'10'">
  ------
</div> 
4. Margin in px
<div [style.margin]="'10px 50px 20px 5px'">
  ------
</div>
<div [style.margin-left.px]="'10'">
  ------
</div> 
5. Using percentage %
<div [style.width]="'80%'">
  ------
</div>
<div [style.width.%]="'80'">
  ------
</div> 

4. Multi-Style Binding

For multi-style binding, use syntax as [style]="styleExpression" in HTML element.
1.
<div [style]="'color: #00a400; width: 120px; height: 130px'">
  ------
</div> 
To get mutli-style from variable, create a component property and assign a style expression. Then use property binding with style key.
TS:
myStyle = "color: #00a400; width: 120px; height: 130px"; 
HTML:
<div [style]="myStyle">
  ------
</div> 
2. Create a property in component.
myStyleExp = "background-color: green; font-size: 1.5rem;"; 
In HTML template, bind this property with style.
<p [style]="myStyleExp">
  ------
</p> 

5. Multi-Style Binding using Record

Create a record with style name and its value and assign it to [style].
1.
<div [style]="{width: '120px', height: '130px', 'font-size': '30px'}">
  ------
</div> 
2. For dynamic binding, create a record in component.
styleObj = {width: '120px', height: '130px', 'font-size': '30px'}; 
In HTML template, assign styleObj to [style].
<div [style]="styleObj">
  ------
</div> 

6. Style Binding Conditionally

We can bind style to HTML elements conditionally using ternary operator. Find the code.
HTML code:
<h1 [style.color]="isColorRed ? 'red' : 'green'">
  ConcretePage.com
</h1>
<p [style.font-size.px]="bigFont ? 30 : 10">
  Font Size
</p>
<p [style]="isDarkTheme ? darkThemeStyle : lightThemeStyle">
  Learn style binding in Angular.
</p>
<div [style.background]="imageAvail ? 'url(\'/assets/images/red.gif\')' : 'skyblue'">
  Background
</div> 
TS code:
isColorRed = true;
bigFont = true;
isDarkTheme = true;
darkThemeStyle = { color: 'white', 'background-color': 'black', 'font-size': '25px' };
lightThemeStyle = { color: 'black', 'background-color': 'white', 'font-size': '25px' };
imageAvail = true; 


7. Using NgStyle

1. NgStyle is an attribute directive that updates styles for the containing element. Use [ngStyle] for style binding.
2. Configure styles as key/value separated with colon. Key is style name and value is expression to evaluate styles. Optionally key can be suffixed with .unit such as width.px.
3. Value is obtained by expression and if expression returns ‘null’, that style is removed from the element.
4. Find the examples to use ngStyle.
<h1 [ngStyle]="{'color': isColorRed ? 'red' : 'green'}">
  ConcretePage.com
</h1>
<div [ngStyle]="{'font-size.px': bigFont ? 30 : 10, 'width.px': 150, 'height.px': 80}">
  Font Size
</div>
<div [ngStyle]="{'font-size': bigFont ? '30px' : '10px', 'width': '150px', 'height': '80px'}">
  Font Size
</div>
<p [ngStyle]="isDarkTheme ? darkThemeStyle : lightThemeStyle">
  Learn style binding in Angular.
</p> 

8. NgStyle with Component Method

NgStyle directive is used to set many inline styles dynamically. Setting styles using NgStyle works as key:value pair. key is the style property name and value is the style value.
To get styles from component, create a component method that will return styles conditionally.
getMyStyles() {
    const myStyles = {
       'color': this.colorFlag ? 'black' : 'yellow',
       'font-size.em': this.isSmall ? this.small/5 : this.big/5,
       'background-image': !this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
    };
    return myStyles;
}  
We will observe that more than one style properties are being used as key:value pair separated by comma (,) within {}. This set of style properties has been assigned to a variable myStyles. The NgStyle can be used with bracket [] and bind- keyword. Our method getMyStyles() can be called by ngStyle as below.
<div [ngStyle]="getMyStyles()">
	NgStyle Example
</div>  
In the output our text within <div> will be applied with all the style properties defined in myStyles set. NgStyle directive should be used over style binding when we want to set many inline styles at one time dynamically.

9. Background Image with style and NgStyle

To load background image, the style property background-image is used. Its value is given in the following syntax.

url('images/red.gif')

In inline style binding we can use it as follows.
<div [style.background-image] = "isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'">
	Style Binding Example
</div>  
And while using with NgStyle the key:value pair is created as following.
<div [ngStyle] = "{'background-image': this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'}">
	Style Binding Example
</div>
We need to use backslash (\) here otherwise it will throw error.

10. Complete Example

app.component.html
<button [style.background-color]="colorFlag ? 'cyan' : 'grey'" [style.color]="isRed(8) ? 'red' : 'black'"> Button
</button>

<div [style.font-size.em]="isSmall ? small/8 : big/8"> Font Size Test with em</div>
<div [style.font-size.px]="!isSmall ? small : big"> Font Size Test with px</div>
<div [style.font-size.pt]="isSmall ? small : big"> Font Size Test with pt</div>
<div [style.font-size.%]="!isSmall ? small * 10: big * 10"> Font Size Test with %</div>

<div
  [style.background-image]="isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'">
  Style Binding Example
</div>

<br /><br />
<div [ngStyle]="allRequiredStyles('one')">
  NgStyle Example
</div>
<br /><br />
<div bind-ngStyle="allRequiredStyles('two')">
  NgStyle Example
</div> 
app.component.ts
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app.component.html'
})
export class AppComponent {
  colorFlag = false;
  isSmall = true;
  isBackgroundRed = false;
  small = 10;
  big = 15;
  num = 10;
  isRed(num: number) {
    if (num > 10) {
      return false;
    } else {
      return true;
    }
  }
  allRequiredStyles(styleSet: string) {
    let myStyles;
    if (styleSet == 'one') {
      myStyles = {
        'color': this.colorFlag ? 'black' : 'yellow',
        'font-size.em': this.isSmall ? this.small / 5 : this.big / 5,
        'background-image': !this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
      };
    } else if (styleSet == 'two') {
      myStyles = {
        'color': !this.colorFlag ? 'black' : 'yellow',
        'font-size.em': !this.isSmall ? this.small / 5 : this.big / 5,
        'background-image': this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
      };
    } else {
      myStyles = {
        'background-color': this.colorFlag ? 'cyan' : 'grey',
        'font-size.%': !this.isSmall ? this.small * 10 : this.big * 10
      };
    }
    return myStyles;
  }
} 
Output
Angular Style Binding and NgStyle

11. References

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE







©2024 concretepage.com | Privacy Policy | Contact Us