Skip to content

Control Flow: @if, @for, @switch and @defer

Angular’s @if, @for and @switch blocks replaced *ngIf, *ngFor and *ngSwitch as the recommended way to express control flow in templates. The differences are not cosmetic:

  • No imports. CommonModule is not needed for control flow at all.
  • Better type narrowing. @if (user(); as u) narrows u properly in the block.
  • Smaller and faster. The blocks compile to instructions rather than to directive instances backed by ViewContainerRef and TemplateRef.
  • track is mandatory in @for, which turns the most common list-performance mistake into a compile error.
  • @defer is a template-level code-splitting primitive with no directive equivalent.

The structural directives still work. New code should use the blocks.

@if (order().status === 'shipped') {
<shipped-badge />
} @else if (order().status === 'pending') {
<pending-badge />
} @else {
<cancelled-badge />
}

Any number of @else if blocks, at most one @else.

@if (user.profile.settings.startDate; as startDate) {
<p>Started {{ startDate | date }}</p>
}

Two benefits. Long expressions read better, and — with a nullable value — TypeScript narrows the alias, so startDate inside the block is not | undefined:

@if (currentUser(); as user) {
<p>{{ user.name }}</p> <!-- narrowed; no optional chaining needed -->
}

This is one of the clearest wins over *ngIf, where narrowing through the as variable was less reliable.

@for (order of orders(); track order.id) {
<order-row [order]="order" />
} @empty {
<p>No orders yet.</p>
}

track is required. See Tracking in @for for the full treatment; the short version is that it maps data items to DOM nodes so Angular performs the minimum DOM work, and getting it wrong destroys and rebuilds every row.

Choose a property that uniquely identifies the item — id or uuid. $index is correct for static collections that never change. Tracking the item itself (track order) uses reference identity and should be a last resort: Angular has no way to map data items to DOM nodes and rendering updates get significantly slower.

One meaningful improvement over *ngFor: @for prioritises view reuse. If a tracked property changes while the object reference stays the same, Angular updates the view’s bindings — including component inputs — rather than destroying and recreating the element.

@empty renders when the collection is empty. It must come immediately after the @for block. It replaces the @if (items().length === 0) pattern that so often sat next to a list and drifted out of sync with it.

Variable Meaning
$count Number of items
$index Index of the current row
$first / $last Whether this is the first / last row
$even / $odd Whether the index is even / odd

Alias them with let, which is what makes nesting workable — an inner loop can read the outer loop’s index:

@for (group of groups(); track group.id; let groupIndex = $index) {
@for (item of group.items; track item.id) {
<p>{{ groupIndex }}.{{ $index }} — {{ item.name }}</p>
}
}

@for does not support continue or break. Filter or slice the collection instead — ideally in a computed, so the work is memoised rather than repeated on every check.

@switch (permission()) {
@case ('admin') {
<admin-dashboard />
}
@case ('reviewer')
@case ('editor') {
<editor-dashboard />
}
@default {
<viewer-dashboard />
}
}

Comparison uses ===. There is no fallthrough, so no break is needed — consecutive @case blocks share one body, which is how you express “these values behave the same”. With no matching case and no @default, nothing renders.

@default never; declares that no remaining cases should exist. If the union type gains a member that no @case covers, the template type checker reports an error:

@Component({
template: `
@switch (state) {
@case ('loggedOut') { <button>Log in</button> }
@case ('loggedIn') { <p>Welcome back</p> }
@default never; // error: 'loading' is not handled
}
`,
})
export class Session {
state: 'loggedOut' | 'loading' | 'loggedIn' = 'loggedOut';
}

This is genuinely valuable: adding a state to a union normally means hunting for every place that switches on it, and this turns that hunt into compiler errors.

One important limitation. Exhaustiveness relies on TypeScript’s narrowing, which only works on variables — not on function calls, and therefore not on a signal read. @switch (state()) will not narrow. Assign it first:

@let currentState = state();
@switch (currentState) {
@case ('loggedOut') { … }
@case ('loggedIn') { … }
@case ('loading') { … }
@default never;
}

Given how much modern Angular state is signals, this is the form you will use most of the time.

When the switched expression is nested inside a union, name the expression explicitly: @default never(state);.

@defer splits its contents into a separate bundle loaded on a trigger:

@defer (on viewport; prefetch on idle) {
<revenue-chart [data]="chartData()" />
} @placeholder (minimum 500ms) {
<div class="chart-skeleton"></div>
} @loading (after 100ms; minimum 1s) {
<spinner />
} @error {
<p>The chart could not be loaded.</p>
}

Triggers: on idle (the default), on viewport, on interaction, on hover, on timer(2s), on immediate, and when <expression>. Multiple triggers separated by ; are OR conditions, and a prefetch trigger downloads early while rendering late.

Two conditions must hold or nothing is deferred: the dependencies must be standalone, and they must not be referenced elsewhere in the same file — including from a viewChild query. There is no warning when this is violated.

@defer is covered fully in Angular Performance, and its server-rendering counterpart — hydrate triggers — in SSR and Hydration.

Not control flow, but it belongs alongside it:

@let total = order().lines.reduce((sum, l) => sum + l.amount, 0);
<p>Total: {{ total | currency }}</p>

@let declares a template variable, scoped to its block and the blocks below it. It is genuinely useful for readability, for the @switch narrowing workaround above, and for avoiding repeated signal reads in one template.

It is not a memoisation tool — the expression is re-evaluated on each check. For expensive derivations, use a computed in the component.

Terminal window
ng generate @angular/core:control-flow

The schematic converts *ngIf, *ngFor and *ngSwitch across a project. Two things to check in the review:

  • *ngFor without trackBy becomes track $index. That is behaviour-preserving, but it is the wrong tracking for any list that can be reordered, filtered or have items removed from the middle. Change these to a stable identity.
  • CommonModule imports may become unnecessary — but only remove them if the component uses no other directive or pipe from it.

Mapping:

Old New
*ngIf="cond" @if (cond) { }
*ngIf="cond; else tpl" @if (cond) { } @else { }
*ngIf="user$ | async as user" @if (user(); as user) { } with a signal
*ngFor="let x of xs; trackBy: fn" @for (x of xs; track x.id) { }
*ngFor with an empty check alongside @empty { }
[ngSwitch] / *ngSwitchCase @switch / @case
Mistake Consequence Fix
track $index on a mutable list Full re-render; focus and state lost Track a stable identity
track item (reference) Significantly slower updates Track an id
Method call in an @if or @for expression Re-executed on every check computed
Filtering inline in @for Re-filtered every check computed
@switch (signal()) with @default never; Exhaustiveness does not apply — no narrowing on calls @let first
Expecting break / continue Not supported Filter or slice the collection
@empty not immediately after @for Compile error Move it
@defer with an outside reference Silently eager Remove the reference
Deep nesting of blocks Unreadable, hard to test Extract a child component
@let used as memoisation Re-evaluated each check computed