Reader Stacks

Angular Dynamic Styling: ngClass and ngStyle

ngClass toggles CSS classes based on component state; ngStyle sets individual inline style properties directly. Most components only ever need the former.

Angular gives you two directives for changing an element's appearance from the component class: ngClass for toggling predefined CSS classes, and ngStyle for setting individual style properties directly. They solve different problems and shouldn't be reached for interchangeably.

1. ngClass with an object

The most common pattern — a set of class names as keys, each mapped to a boolean expression:

<div [ngClass]="{ 'is-active': isActive, 'is-disabled': isDisabled }">
  Item
</div>

Each class is added when its expression is truthy and removed when it's falsy — Angular re-evaluates this on every change detection cycle, so the classes stay in sync with component state automatically, with no manual DOM manipulation.

2. ngClass with an array or string

<div [ngClass]="['card', 'card--elevated']"></div>
<div [ngClass]="statusClass"></div>
get statusClass(): string {
  return this.order.status === 'shipped' ? 'badge badge--success' : 'badge badge--pending';
}

For a single conditional class, the plain class-binding syntax is simpler than ngClass and does the same thing:

<div [class.is-active]="isActive"></div>

3. ngStyle

<div [ngStyle]="{ 'background-color': themeColor, 'width.px': progressWidth }"></div>

The 'width.px' syntax is a unit suffix — Angular appends px to whatever number progressWidth evaluates to. This is genuinely useful for values computed at runtime (a progress bar width, a color picked from user input) that can't reasonably live in a static CSS class.

4. Why ngClass is usually the better default

Reaching for ngStyle to toggle a color or a border, when a CSS class could express the same thing, moves styling logic out of your stylesheet and into the component — it becomes harder to theme, harder to override, and harder for someone reading the template to predict without also reading the component class. ngClass keeps the actual style rules in CSS, where a browser dev tools inspector or a future redesign can find them, and the component only decides which named state applies.

A reasonable rule: use ngClass for anything expressible as a finite set of states (active/disabled/error, small/medium/large), and reserve ngStyle for genuinely continuous or dynamic values you can't enumerate in advance.

Topics: Developer Productivity