Sub topic 13
Migrating from *ngIf, *ngFor, and ngSwitch
This chapter assumes you know TypeScript, Angular components and templates, property and event binding, and the basics of signals or observables. You should also have read the earlier chapters on @if, @for, and @switch. Here you will map each old structural directive to its built-in block, use the automated schematic, and review the results.
Why migrate
Structural directives (*ngIf, *ngFor, ngSwitch) are ordinary directives that live in CommonModule. They need imports, and they rely on <ng-template> references for alternatives. The built-in blocks are part of the template syntax itself.
| Concern | Structural directives | Built-in control flow |
|---|---|---|
| Import needed | `NgIf`, `NgFor`, `NgSwitch` (or `CommonModule`) | None |
| Alternative content | `else templateRef` plus `<ng-template #ref>` | `@else { ... }` |
| Identity of list items | Optional `trackBy` function | Required `track` expression |
| Empty list | A separate `*ngIf` | `@empty { ... }` |
| Switch matching | `ngSwitchCase` (strict equality) | `@case` (strict equality) |
The old directives still work, so migration is optional. Migrating is worthwhile because the new syntax is shorter and needs fewer imports. It also forces you to write a track expression for every loop.
Mapping each construct
*ngIf to @if
A plain *ngIf becomes an @if block. The else template reference becomes an @else block placed directly after the closing brace.
<!-- Before -->
<div *ngIf="items.length; else none">
<app-item *ngFor="let item of items; trackBy: trackById" [item]="item" />
</div>
<ng-template #none><p>No items.</p></ng-template>
<!-- After -->
@if (items.length) {
@for (item of items; track item.id) {
<app-item [item]="item" />
}
} @else {
<p>No items.</p>
}Notice three changes. The wrapper <div> disappears, because a block does not need a host element. The <ng-template #none> is gone. The trackBy function is replaced by track item.id.
The as alias
*ngIf="user$ | async as user" becomes @if (user$ | async; as user). The separator is a semicolon, not a space.
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, of } from 'rxjs';
interface User {
name: string;
}
@Component({
selector: 'app-profile',
imports: [AsyncPipe],
template: `
@if (user$ | async; as user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading profile...</p>
}
`,
})
export class ProfileComponent {
user$: Observable<User> = of({ name: 'Ada' });
}AsyncPipe is still imported, because pipes are not part of control flow. The as variable exists only inside the @if block. It is not visible in the @else block.
*ngFor to @for
Every *ngFor option has a counterpart:
| `*ngFor` | `@for` |
|---|---|
| `let item of items` | `item of items` |
| `trackBy: fn` | `track expression` |
| `let i = index` | `let i = $index` |
| `let first = first` | `let f = $first` |
| `let last = last` | `let l = $last` |
| `let even = even` | `let e = $even` |
| `let odd = odd` | `let o = $odd` |
| `let count = count` | `let c = $count` |
| separate `*ngIf` for an empty list | `@empty { ... }` |
The context variables $index, $count, $first, $last, $even, and $odd are available inside the block without aliases. You only need let when you want a different name, for example when a nested loop would otherwise shadow the outer $index.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-list',
template: `
<ul>
@for (task of tasks(); track task.id; let i = $index, isEven = $even) {
<li [class.striped]="isEven">{{ i + 1 }}. {{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
`,
})
export class TaskListComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Write spec' },
{ id: 2, title: 'Review pull request' },
]);
}Choosing the track expression
trackBy was optional, and many templates never used it. @for requires track, so the migration has to pick something for every loop. Use these rules:
- If items have a unique, stable identifier such as
id, usetrack item.id. - If the collection holds primitive values that are unique, use
track item. - If neither exists and the list never reorders,
track $indexis acceptable.
Tracking by $index means Angular reuses DOM nodes by position. When the list is reordered or filtered, the nodes stay in place and only their bindings change. That can cause lost input focus or restarted animations. Prefer a real identity whenever one exists.
ngSwitch to @switch
[ngSwitch] with *ngSwitchCase and *ngSwitchDefault becomes @switch with @case and @default.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-request-status',
template: `
@switch (status()) {
@case ('loading') {
<p>Loading...</p>
}
@case ('error') {
<p>Something went wrong.</p>
}
@default {
<p>Data is ready.</p>
}
}
`,
})
export class RequestStatusComponent {
status = signal<'loading' | 'error' | 'ready'>('loading');
}Both versions compare with strict equality and render only the first match. The new syntax has no fall-through, so each @case needs its own content. If two values should show the same content, you need to repeat it or move it into a child component.
Running the schematic
Angular ships a schematic that rewrites templates for you. Run it from the root of the workspace:
ng generate @angular/core:control-flowThe schematic asks for a path, so you can migrate one folder at a time. It handles inline templates inside @Component decorators and separate .html files. For *ngFor loops without a trackBy, it generates track $index, which preserves the old behavior but is not always the best choice. It also removes unused NgIf, NgFor, and NgSwitch imports from standalone components where it can.
Reviewing the output
The schematic does not understand your data, so check these points in the diff:
track $indexplaceholders. Replace them withtrack item.idor similar where an identifier exists.- Removed wrapper elements. The schematic may leave
<ng-container>elements in place. Remove them if they only existed to hold a directive. - Whitespace. Block syntax can change the whitespace around content. Check snapshot tests and layout that depends on inline spacing.
- Leftover imports. Remove any
CommonModule,NgIf, orNgForimports that nothing else in the component uses. KeepAsyncPipe,DatePipe, and other pipes that you still use.
Differences that can change behavior
Most migrations are mechanical, but a few differences matter.
Directives on the same element
*ngIf and *ngFor could not be placed on one element, which forced a wrapper <ng-container>. With blocks, nest them directly. The condition goes outside or inside depending on what you want, and the order is explicit.
@for (order of orders; track order.id) {
@if (order.isOpen) {
<app-order [order]="order" />
}
}Other structural directives
*ngTemplateOutlet, *ngComponentOutlet, and custom structural directives are not replaced by control flow. Leave them as they are. Only *ngIf, *ngFor, and ngSwitch have built-in equivalents.
Template reference variables
A template reference variable (#name) declared inside a block is scoped to that block. If an old template declared a reference inside an *ngIf and used it outside, it already failed. The same rule applies to the new syntax, so check any references that cross a block boundary.
Performance
The built-in @for uses an optimized diffing algorithm, and track is compiled into the generated code. In most apps you will see equal or better rendering of large lists. Do not migrate for speed alone, and measure if a specific list matters.
A checklist
- Commit a clean tree on a new branch.
- Run
ng generate @angular/core:control-flowfor one directory. - Replace every
track $indexthat has a better identity. - Remove unused
CommonModule,NgIf,NgFor, andNgSwitchimports. - Run unit tests, the build, and a manual check of pages with lists.
- Commit, then repeat for the next directory.
Exercise
Convert this template to built-in control flow, and choose a track expression. Assume each user has a unique id.
<ul ngIf="users.length; else empty">
<li ngFor="let user of users; let i = index; trackBy: trackById">{{ i }}: {{ user.name }}</li>
</ul>
<ng-template #empty><p>No users.</p></ng-template>
Show answer
@if (users.length) {
<ul>
@for (user of users; track user.id) {
<li>{{ $index }}: {{ user.name }}</li>
}
</ul>
} @else {
<p>No users.</p>
}
The trackBy function becomes track user.id. The index variable is available as $index without an alias. The <ng-template #empty> is replaced by @else. You could also drop the outer @if and use @empty inside the @for, but then the empty <ul> would still render.
Exercise
The schematic converted a loop to @for (row of rows; track $index). The rows have a unique rowId, can be sorted by the user, and each row contains a text input. What problem can track $index cause here, and what should you write instead?
Show answer
With track $index, Angular reuses DOM nodes by position. After sorting, the nodes stay where they are and only their bindings change, so text typed into an input or the focus can end up attached to the wrong row. Use track row.rowId so each DOM node follows its row when the order changes.