Skip to main content

What does ngStyle do?

The [ngStyle] directive in Angular is an attribute directive that lets you dynamically change an element's CSS styles through an object of keys and values.

How it works:

  1. [ngStyle] accepts an object where the key is the CSS property name and the value is its value.
  2. Styles are applied dynamically and update when the data changes.

Example:

html
<div [ngStyle]="{'color': textColor, 'font-size.px': fontSize}"> Dynamic style </div>
typescript
textColor = 'red'; fontSize = 20;

Conclusion: ngStyle lets you change individual CSS properties of an element depending on the component's state, without using classes.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.