skip to Main Content

What’s that difference between using [ngStyle] and [style.<attr>] for inline styling components in Angular?

2

Answers


  1. Chosen as BEST ANSWER
    1. The main & obvious difference between [ngStyle] & [style] is in the output:

      • using [style.color]="condition ? 'black' : ''" will add a inline color style to the element in ALL the conditions (true or false)
      • but using [ngStyle]="condition && {'color':'black'}" will add a inline color style to the element ONLY when the condition is true
    2. Other than this, [ngStyle] helps in styling with multiple conditions for a better developer experience. For example:

      • using [style.<attr>]: <div [style.color]="hasError ? 'red' : 'black' " [style.font]="font" [style.background-color]="hasError ? 'tomato' : 'white' ">

      • using [ngStyle]:

        <div [ngStyle]="currentStyles">
        
        this.currentStyles = {     
            'font-style':  this.canSave  ? 'italic' : 'normal',  
            'color':       this.hasError ? 'red'   : 'black',     
            'font-size':   this.hasError ? '24px'   : '12px'   
        };
        

    References:


  2. In Angular, you can use either [ngStyle] or [style.<attr>] to apply inline styles to components. While both methods achieve similar results, there are key differences:

    [ngStyle]

    • Accepts an object with CSS property names as keys and values as values.
    • Can be used to set multiple styles at once.
    • Supports property binding, allowing for dynamic style updates.

    Example:

    <div [ngStyle]="{'background-color': 'blue', 'color': 'white'}"> test text </div>
    

    [style.<attr>]

    • Accepts a single CSS property value.
    • Can be used to set a single style attribute.
    • Also supports property binding for dynamic updates.

    Example:

    <div [style.background-color]="'blue'" [style.color]="'white'"> test text </div>
    

    Key differences:

    • Multiple styles: [ngStyle] allows setting multiple styles at once, while [style.<attr>] requires separate bindings for each style attribute.

    • Object vs. single value: [ngStyle] expects an object, whereas [style.<attr>] expects a single value.

    • Readability and maintainability: For simple, single-style attributes, [style.<attr>] might be more readable. For multiple styles or more complex scenarios, [ngStyle] can be more convenient.

    Ultimately, the choice between [ngStyle] and [style.<attr>] depends on your specific use case, personal preference, and the complexity of your styling needs.

    Note: For more detail please take reference from here https://blog.angulartraining.com/whats-the-difference-between-style-and-ngstyle-in-angular-68a3301c2ae6

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search