Definition
The ngStyle directive is used to apply dynamic styles to elements based on expressions. It allows you to bind a style property to an element.


How to Use ngStyle

  • String Expression
    You can bind a string of CSS styles directly:

    <h2 [style]="'backgroundColor:yellow;'">Test by MSA</h2>
    <h2 [style]="'background-color:yellow;'">Test by MSA</h2>
    <h2 [style]="'background-color:yellow; color:red'">Test by MSA</h2>
  • Object Expression
    You can bind a JavaScript object to dynamically set multiple styles:

    <h2 [style]="{'color': 'orange', 'fontFamily': 'cooper'}">Test by MSA</h2>

1. Example Using Object

Component (TS)

myStyles = {
  'color': 'orange',
  'fontFamily': 'cooper',
  'font-size': '45px'
};

HTML

<h2 [style]="myStyles">Test by MSA</h2>

2. Example Using Specific Style Properties

  • Bind specific style properties directly:

    <h2 [style.color]="'green'">Test by MSA</h2>
    <h2 [style.fontSize.px]="'60'">Test by MSA</h2>

Key Concepts

  • Single Style Binding
    To create a single style binding, use the style prefix followed by a dot and the CSS property name:

    <h2 [style.width]="width">Test by MSA</h2>
  • Toggle Multiple Styles
    To toggle multiple styles, bind to the [style] attribute:

    <h2 [style]="styleExpression">Test by MSA</h2>
    • styleExpression can be:
      • A string of CSS styles, e.g., "width: 100px; height: 100px; background-color: cornflowerblue;".
      • An object or conditional expressions using ternary operators.
  • ngStyle Alternative
    You can use the ngStyle directive as an alternative to [style]:

    <div [ngStyle]="myStyles">Test by MSA</div>

Notes

  • Multiple Styles in a Div
    You can apply multiple styles to a <div> element:

    <div [style.color]="'green'" [style.text-align]="'center'">Test</div>
  • Array Binding Not Supported
    Binding an array to [style] is not supported.