Class & Style Binding

Conditional CSS Without Manual Toggling

Class & Style Binding

Angular has three syntaxes for binding CSS classes, mirrored for inline styles, so you never write classList.toggle in a component again.

3 min read Level 1/5 #angular#templates#css
What you'll learn
  • Bind a single class with [class.foo]
  • Use the object form to toggle several at once
  • Apply the same patterns to inline styles

Angular’s CSS bindings let you turn classes on and off — and inline styles up and down — straight from the template.

Toggling a Single Class

<button [class.active]="isActive()">Tab</button>
<li [class.done]="todo.done">{{ todo.text }}</li>

The class is added when the expression is truthy, removed when it isn’t. This is the shortest, most readable form for one class at a time.

Toggling Many Classes — Object Form

<div [class]="{ open: isOpen(), pinned: isPinned(), error: hasError() }">
  ...
</div>

Each key is a class name; each value is a boolean expression. Angular diffs the object on every change and adjusts the element’s class list.

Inline Styles

The mirror syntax sets individual style properties:

<div [style.color]="textColor()">Hi</div>
<div [style.width.px]="size()">box</div>

<div [style]="{
  backgroundColor: bg(),
  'font-size.px': fs(),
  opacity: faded() ? 0.5 : 1
}">
  styled
</div>

Notice the .px, .em, or .% suffix — Angular appends the unit for you so you can keep the number as a number in the component.

When to Use What

  • One class on/off → [class.foo]="cond"
  • Several classes at once → [class]="{ a: x, b: y }"
  • A dynamic value like a theme color → [style.color]="theme()"
  • A handful of styles together → [style]="{...}" object form

Reach for a stylesheet class first; reach for inline styles only when the value is dynamic and can’t sensibly be expressed as a class name.

New Control Flow — @if, @for, @switch →