Lesson 8 / 30

@if, @for & @switch

The modern built-in control-flow syntax.

@if / @else

Since Angular 17, @if and @else are built into the template compiler — no directive import needed.

@if (isLoggedIn) {
  <p>Welcome back!</p>
} @else {
  <p>Please log in.</p>
}

@for with track

@for requires a track expression so Angular can efficiently update the DOM when the list changes.

@for (item of cartItems; track item.id) {
  <li>{{ item.name }}</li>
} @empty {
  <li>Your cart is empty.</li>
}

@switch

@switch picks one of several @case blocks, with an optional @default.

@switch (status) {
  @case ('loading') { <p>Loading…</p> }
  @case ('error')   { <p>Something went wrong.</p> }
  @default          { <p>Ready.</p> }
}

Older syntax you'll still see

Older code uses structural directives *ngIf and *ngFor instead. They still work, but @if/@for are recommended for new code — no import, and better performance.

Quick check: What does `@for` require that `*ngFor` did not strictly enforce?

  • A `track` expression
  • An `@empty` block
  • An array wrapped in a Signal
Answer

A `track` expression — `track` is mandatory in `@for` and helps Angular identify items efficiently across re-renders.