Skip to main content

How to set a dynamic style in a template?

In Angular, a dynamic style in a template is set using the [ngStyle] directive or a binding to an individual style property.

Via [ngStyle]

Allows passing an object with CSS properties:

html
<div [ngStyle]="{ 'color': textColor, 'font-size.px': fontSize }"> Text with a dynamic style </div>
  • textColor and fontSize are component properties.
  • .px, .em, etc. are added to properties to specify units.

Via binding to an individual style

You can bind a specific CSS property directly:

html
<div [style.background-color]="bgColor"> A block with a dynamic background </div> <div [style.width.px]="blockWidth"> A block with a dynamic width </div>
  • [style.<style-name>] binds a specific CSS property to an expression from the component.
  • Units can be specified via suffixes (.px, .em, etc.).

This way, Angular allows changing element styles depending on the component's state or data.

Short Answer

Interview ready
Premium

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