Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 74 ยท Templates and Data Binding

Control Flow: @if, @for and @switch

Learn Angular's built-in control flow blocks - @if/@else, @for with track and @empty, @switch, @let - why track matters, and how to migrate from *ngIf and *ngFor.

A template is not only fixed markup. You need to show a loading message or the data, repeat a row for every item, or pick one panel out of several. Angular templates handle all three with control flow blocks: @if, @for and @switch. They look like JavaScript statements with curly braces, they are part of the template language itself (no imports needed), and they replaced the older *ngIf and *ngFor directives.

This lesson walks through each block, the contextual variables inside @for, the track expression and why it matters, the @let declaration, and how to migrate old templates. It builds on interpolation and property binding.

The Angular compiler is not available on this site, so all Angular code is read-only. The runnable <TryIt> examples are stand-ins that re-create the idea in plain TypeScript and JavaScript: a diffing list renderer and a DOM demo of node reuse.

@if, @else if and @else

HTML
@if (user(); as u) {
  <p>Signed in as {{ u.name }}</p>
} @else if (isLoading()) {
  <p>Loading...</p>
} @else {
  <p>Please sign in.</p>
}

The condition is any template expression. If it is truthy, that block is added to the page; otherwise it is skipped (and if it was showing, it is removed: the elements are destroyed, not hidden). @else if and @else work as you expect, and a chain stops at the first match.

The ; as u part saves the condition's value in a name usable inside the block. It is handy because user() may be null in the other branches, and inside the @if block TypeScript knows u is not null, so u.name type-checks.

Because the block is removed rather than hidden, any component inside is created and destroyed as the condition flips, and its signals and local state are lost. If you only want to hide something visually and keep its state, use a [hidden] property binding or a CSS class instead (Property, Attribute, Class and Style Binding).

@for and track

HTML
<ul>
  @for (task of tasks(); track task.id) {
    <li>{{ task.title }}</li>
  } @empty {
    <li>Nothing to do.</li>
  }
</ul>

@for (item of collection; track expression) renders the block once per item. Three things to know:

  1. The collection can be an array or any iterable, such as a Set or Map's values.
  2. track is required. Angular will not compile a @for without it. This is deliberate: it forces you to think about identity.
  3. @empty is an optional block shown when the collection has no items, which saves a separate @if check.

Contextual variables

Inside the loop, these are available automatically, and you can alias them with let:

Variable Meaning
$index Zero-based position of the current item
$count Number of items in the collection
$first, $last true for the first or last item
$even, $odd true for even or odd positions
HTML
@for (row of rows(); track row.id; let i = $index, last = $last) {
  <tr [class.total]="last">
    <td>{{ i + 1 }}</td>
    <td>{{ row.label }}</td>
  </tr>
}

You can use $index and friends directly, or give them short names with let name = $variable, separated by commas.

Why track matters

When the list changes, Angular compares the old and new collection and must decide: which DOM nodes can be reused, which are new, which must be removed, and which only moved. The track expression is the identity of an item. Items with the same tracking value are "the same item", so Angular keeps their DOM nodes, their child components and their local state (an input's text, focus, scroll position, a running animation) and only moves or updates them.

  • track task.id is the right choice for items with a stable unique id. Reordering moves nodes instead of rebuilding them.
  • track $index ties identity to position. It is fine for a list that is never reordered or filtered (for example a fixed set of labels), but when items move, the node at position 0 is simply handed a different item, which can leave stale state behind.
  • Tracking by the object itself (track item) works when the same object instances persist. If you replace objects with fresh copies from a server on every refresh, every row is considered new, and the whole list is rebuilt.

The next stand-in is a keyed diff. It takes the old and new lists and reports what a renderer would do with each tracking rule. It is far simpler than Angular's real reconciliation algorithm, but the ideas (create, reuse, move, destroy) are the same.

TypeScript Keyed diffing: track by id or by index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

With track item.id, one node is created for Margaret and the other three are reused, merely reordered. With track $index, no node is ever moved: node 0 just receives "Margaret" as new text, node 1 receives "Linus", and so on, so every row is rewritten and the last position is created new. For plain text rows that is cheap, but if each row contained a component with an input box, the typed text would stay in the box at position 0 while the data around it changed. The next example shows exactly that bug.

DOM node reuse you can see

This HTML stand-in renders a list of rows, each with a text box. Type something into a box, then press "Shuffle" and compare the two modes. Keyed mode keeps each box with its person; index mode leaves the text behind in the same position.

Keyed and index rendering with typed state

Real Angular's reconciler is more sophisticated, but the lesson holds: identity decides what survives an update.

@switch

Use @switch when one value selects among several fixed alternatives:

HTML
@switch (status()) {
  @case ('loading') {
    <p>Loading...</p>
  }
  @case ('error') {
    <p class="error">Something went wrong.</p>
  }
  @case ('ready') {
    <app-table [rows]="rows()" />
  }
  @default {
    <p>Unknown state.</p>
  }
}

Each @case is compared with the switch value using strict equality (===). There is no fall-through, so you do not write break. @default is optional. For a union type such as 'loading' | 'error' | 'ready', a long @if / @else if chain does the same job, but @switch states the intent more clearly.

@let: naming a value in the template

@let declares a read-only variable inside a template, so you can compute something once and use it in several places:

HTML
@let fullName = user().first + ' ' + user().last;
@let total = price() * quantity();

<h2>{{ fullName }}</h2>
<p>Total: {{ total }}</p>

It can also unwrap an async pipe result once instead of subscribing several times: @let user = user$ | async;. A @let variable cannot be reassigned, and it is visible only in the template where it is declared and in the child blocks below it. Use it to avoid repeating a long expression, not to hide heavy logic; computations that matter belong in a computed() signal (Signals: signal, computed and effect).

Migrating from *ngIf and *ngFor

Older Angular code uses structural directives:

HTML
<!-- legacy -->
<li *ngFor="let task of tasks; trackBy: trackById; let i = index">{{ task.title }}</li>
<p *ngIf="user; else guest">Hello</p>
<ng-template #guest><p>Please sign in.</p></ng-template>

They still work in current versions if you import NgIf, NgFor or CommonModule, but the built-in blocks are the recommended style, and the older directives are deprecated. Why the change: control flow blocks need no imports, read like normal code and type-check more precisely. Mapping:

Legacy New
*ngIf="x" @if (x) { }
*ngIf="x; else other" @if (x) { } @else { }
*ngFor="let i of items; trackBy: fn" @for (i of items; track i.id) { }
let i = index let i = $index
[ngSwitch] and *ngSwitchCase @switch and @case

You do not have to rewrite by hand: the Angular CLI includes an automatic migration, ng generate @angular/core:control-flow, that converts a project's templates. Review the diff afterwards, particularly the track expressions it picks.

flowchart LR
  A["Template with blocks"] --> B["Compiler"]
  B --> C["@if: add or remove a view"]
  B --> D["@for: reconcile views by track key"]
  B --> E["@switch: pick one view"]

The compiler turns each block into instructions that add, remove or reconcile pieces of the page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to the content of an @if block when its condition becomes false?

    Blocks are added and removed, not hidden. Components inside are created and destroyed as the condition flips, so their local state is lost.
  2. 2. Why does @for require a track expression?

    track gives each item an identity. Without it Angular could not know whether an item moved, changed or is new.
  3. 3. A list of rows with text inputs can be reordered by the user. Which track expression is the best choice?

    A stable id keeps each row's node and typed text with its item when rows move. $index would leave the text at the old position.
  4. 4. How do you show a message when a collection is empty?

    @empty is an optional block attached to @for that renders when the collection has no items.

Summary

  • @if, @else if and @else add or remove parts of the template; ; as name saves the condition's value.
  • @for (x of xs; track key) requires track; @empty handles empty collections.
  • Inside @for, $index, $count, $first, $last, $even and $odd are available, and let can alias them.
  • A good track expression is a stable id; track $index only suits lists that never reorder.
  • @switch selects one @case using strict equality; @let names a value for reuse in the template.
  • *ngIf and *ngFor are the legacy forms; ng generate @angular/core:control-flow migrates them.
  • The runnable examples are stand-ins; the Angular snippets are read-only.

Next: Pipes