TExcelTAD
Home › Angular › Control Flow (@if, @for, @switch)

Control Flow: @if, @for, @switch

Templates often need to show something only under a condition, repeat a block for every item of a list, or choose one of several views. Angular's built-in control flow blocks do exactly that, with syntax that reads almost like TypeScript.

Block Purpose
@if (cond) { } @else if (other) { } @else { } Conditional rendering
@for (item of items; track item.id) { } @empty { } Repeat for each item
@switch (value) { @case (a) { } @default { } } Choose one of several blocks

Note: Older code uses the structural directives *ngIf, *ngFor and [ngSwitch]. They still work, but the block syntax is the recommended way and needs no imports.

@if

angular · try it yourself
import { Component, signal } from '@angular/core';

interface User { name: string; role: 'admin' | 'member'; }

@Component({
  selector: 'app-welcome',
  template: `
    @if (user(); as u) {
      <p>Signed in as <strong>{{ u.name }}</strong></p>
      @if (u.role === 'admin') {
        <button>Open admin panel</button>
      } @else {
        <small>Member account</small>
      }
    } @else {
      <button>Sign in</button>
    }
  `,
})
export class Welcome {
  user = signal<User | null>({ name: 'Ana', role: 'admin' });
}

as u stores the result of the condition in a local variable — perfect for signals that may hold null, because inside the block u is known to be non-null.

@for and track

@for requires a track expression. It gives each item a stable identity so that when the list changes, Angular moves, adds or removes only the affected DOM nodes instead of rebuilding everything. Track by a unique id when items have one; use $index only for static lists.

Inside the block you also get contextual variables:

Variable Meaning
$index Position of the item (0-based)
$first / $last Is this the first / last item?
$even / $odd Is the index even / odd?
$count Total number of items
angular · try it yourself
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-leaderboard',
  template: `
    <ol>
      @for (p of players(); track p.id; let i = $index, last = $last) {
        <li [class.top]="i === 0">
          {{ p.name }} — {{ p.points }} pts
          @if (last) { <em>(keep going!)</em> }
        </li>
      } @empty {
        <li>No players yet.</li>
      }
    </ol>
  `,
  styles: `.top { font-weight: bold; color: #dd0031; }`,
})
export class Leaderboard {
  players = signal([
    { id: 7, name: 'Minh', points: 980 },
    { id: 3, name: 'Priya', points: 870 },
    { id: 12, name: 'Jonas', points: 640 },
  ]);
}

@empty renders when the collection has no items — no separate @if needed.

Why tracking matters

Tracking is a diffing problem: given the old and new list, which items stayed, which are new and which disappeared? This plain TypeScript function does a simplified version of what Angular does with your track key:

ts · try it yourself
interface Item { id: number; label: string; }

function diffByKey(oldList: Item[], newList: Item[]) {
  const oldIds = new Set(oldList.map((i) => i.id));
  const newIds = new Set(newList.map((i) => i.id));
  return {
    kept: newList.filter((i) => oldIds.has(i.id)).map((i) => i.label),
    added: newList.filter((i) => !oldIds.has(i.id)).map((i) => i.label),
    removed: oldList.filter((i) => !newIds.has(i.id)).map((i) => i.label),
  };
}

const before: Item[] = [{ id: 1, label: 'Write' }, { id: 2, label: 'Test' }, { id: 3, label: 'Ship' }];
const after: Item[] = [{ id: 3, label: 'Ship' }, { id: 1, label: 'Write' }, { id: 4, label: 'Celebrate' }];

console.log(diffByKey(before, after));
{
  kept: [ 'Ship', 'Write' ],
  added: [ 'Celebrate' ],
  removed: [ 'Test' ]
}

Two existing DOM nodes are reused (just moved), one is created and one removed. Without a good key, Angular would have to assume everything changed.

@switch

@switch compares a value with each @case using === and renders the first match, or @default:

angular · try it yourself
import { Component, signal } from '@angular/core';

type Status = 'loading' | 'ready' | 'error';

@Component({
  selector: 'app-status',
  template: `
    @switch (status()) {
      @case ('loading') { <p>⏳ Loading data…</p> }
      @case ('ready') { <p>✅ {{ count() }} records loaded</p> }
      @case ('error') { <p class="err">❌ Could not load data</p> }
    }
  `,
})
export class StatusPanel {
  status = signal<Status>('ready');
  count = signal(128);
}

Tip: With a union type like Status, the compiler checks your @case values — a typo such as 'redy' is reported at build time.

Test yourself

Which part of @for is mandatory?

  1. let i = $index
  2. track
  3. @empty
  4. as

What does @empty do inside a @for block?

  1. Clears the list
  2. Renders its content when the collection has no items
  3. Skips null items
  4. Runs after the last item

What is the best track expression for a list of orders with unique id fields?

  1. track $index
  2. track order
  3. track order.id
  4. track true