Sub topic 1
Why Angular has built-in control flow
Almost every template has to decide what to show. It may show a panel only when a user is logged in, repeat a row for each item in a list, or pick one of several views based on a status. Angular templates are declarative, so they need a way to express this logic. This chapter explains how Angular handled it before version 17, why the framework added its own syntax, and what the new blocks look like. Later chapters cover each block in detail.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript syntax: classes, interfaces, and union types.
- How an Angular component and its template fit together, including the
@Componentdecorator. - Interpolation (
{{ value }}), property binding ([class.striped]="flag"), and event binding ((click)="handler()"). - What a signal is. Signals are helpful but not required. The examples call a signal like a function (
isLoggedIn()) to read its value and use.set()to change it. Observables appear only briefly.
You need Angular 17 or later to run the examples. The blocks are stable from Angular 18.
The problem with directive-based control flow
Before Angular 17, conditionals and loops were built from structural directives. A structural directive is a directive that adds or removes parts of the DOM, and you write it with a leading asterisk. The three you used most were *ngIf, *ngFor, and ngSwitch with *ngSwitchCase. They worked, but they had costs.
- Imports. The directives live in
@angular/common. A standalone component had to listNgIf,NgFor, orNgSwitchin itsimportsarray, or importCommonModule. If you forgot, Angular reported an unknown property or unknown element error. The cause was not obvious to newcomers. - Indirect syntax. The asterisk is shorthand. Angular rewrites
*ngIf="cond; else other"into an<ng-template>with a boundngIfinput, and theelsebranch has to be a separate<ng-template>referenced by a template variable. You had to know the desugaring to understand whyelsetakes a template reference rather than markup. - Wrapper elements. To combine two directives on one element, or to apply a directive to several siblings, you needed
<ng-container>. Angular does not allow two structural directives on the same element. - Optional performance hints.
*ngForre-creates DOM nodes when item identity changes. ThetrackByfunction that prevents this was optional, so many templates left it out. - Runtime cost. Directives are classes. Each use creates a directive instance, runs change detection hooks, and goes through the dependency injection system.
None of these is fatal. Together they made templates noisier than the logic they expressed.
What the built-in blocks are
Angular 17 introduced a block syntax that the template compiler understands directly. A block starts with @, followed by a keyword, an optional parenthesized expression, and a body in curly braces.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-session',
template: `
@if (isLoggedIn()) {
<p>Welcome back!</p>
<button (click)="isLoggedIn.set(false)">Log out</button>
} @else {
<button (click)="isLoggedIn.set(true)">Log in</button>
}
`,
})
export class SessionComponent {
isLoggedIn = signal(false);
}This component has no imports array and no <ng-template>. The @else branch is written inline, directly after the closing brace of the @if body. Angular provides these blocks:
| Block | Purpose | Replaces |
|---|---|---|
| `@if`, `@else if`, `@else` | Render one branch based on a condition | `*ngIf` with `else` |
| `@for`, `@empty` | Render a template per item, with a fallback for no items | `*ngFor` |
| `@switch`, `@case`, `@default` | Pick one template by comparing a value | `ngSwitch`, `*ngSwitchCase`, `*ngSwitchDefault` |
Angular also has a separate block family for deferred loading (@defer). It is not part of this tutorial.
How the blocks differ from directives
The syntax is shorter, but the more important difference is where the logic lives. A structural directive is a runtime class that Angular instantiates. A control flow block is part of the template language. The compiler turns each block into low-level template instructions when your application is built, so no directive class is involved.
Rather than use the empty fence above, the diagram below shows the two paths.
Four practical consequences follow.
- No imports. Blocks are always available in every component template, standalone or module-based. There is nothing to forget.
- No host element. A directive is attached to an element or an
<ng-template>. A block wraps its content and produces no element of its own, so the DOM contains only what you wrote inside the braces. - Real
else. The alternative branch is ordinary markup in the template, not a reference to a template variable. - Compile-time checking. The compiler knows the structure of the block, which helps with type narrowing and with errors such as a missing
trackexpression.
Required tracking in `@for`
The loop block makes one decision for you. It requires a track expression, which tells Angular how to identify each item across updates. Angular uses the identity to decide which existing DOM nodes to reuse when the collection changes. In *ngFor, the equivalent trackBy was optional. Making it required moves a common performance problem from a silent default to a compile error.
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' },
]);
}This one block already shows several features covered later: track task.id, implicit variables like $index and $even bound to local names with let, and an @empty branch for a collection with no items. A later chapter explains how to choose a good track expression.
Side by side with the old syntax
The following snippet shows the same template written both ways.
<!-- 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>
}Compare the two versions:
else noneplus<ng-template #none>becomes@else { ... }.trackBy: trackByIdneeds a method on the component class.track item.idis an expression written in place.- The wrapper
<div>is no longer needed to hold the directive, although you may keep an element if you want one for layout.
The old directives still work. NgIf, NgFor, and NgSwitch are not removed, and existing templates keep compiling. Angular's guidance, though, is to prefer the built-in blocks in new code, and a CLI schematic can convert old templates:
ng generate @angular/core:control-flowThe last chapter of this tutorial covers migration, including what to review after the schematic runs.
Working with observables
Blocks do not change how you consume observables. You still use the async pipe, and the as clause on @if keeps the resolved value for use inside the block. This avoids subscribing twice.
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' });
}Note that AsyncPipe still needs to be imported, because it is a pipe, not a block. Only the control flow itself is built in.
A syntax gotcha: literal `@` and braces
Because @ and { } now have meaning in templates, you cannot type them as plain text where the parser might read a block. For example, a literal @ followed by a word can be read as a block name, and a stray closing brace can end a block early. Write these characters as HTML entities instead:
| Character | Entity |
|---|---|
| `@` | `@` |
| `{` | `{` |
| `}` | `}` |
For example, write support@example.com when you want that text to appear in the page. Text inside quoted attribute values and inside {{ }} interpolation is a separate context, so strings there are unaffected.
What to expect from the rest of the tutorial
The remaining chapters take each block in turn: @if with @else if and @else, aliases with as, @for with track, the implicit variables, @empty, @switch, how blocks narrow types, nesting, common mistakes, and migration. This chapter's job was to explain why the blocks exist. They remove imports and <ng-template> plumbing, they are compiled rather than instantiated, and they make track mandatory.
Exercise
A teammate says "@if is just *ngIf with different punctuation." Give two concrete differences between a built-in block and a structural directive, and state what each difference changes in a component you write.
Show answer
First, blocks need no import. A standalone component using *ngIf must list NgIf (or CommonModule) in imports, while @if works with no entry. Second, @else is inline markup, whereas *ngIf needs else to point at a separate <ng-template #name>. Other valid differences: blocks are compiled into template instructions instead of being directive instances, and @for requires a track expression while trackBy in *ngFor was optional.
Exercise
Rewrite this template with built-in control flow, using item.id as the identity:
<ul>
<li ngFor="let item of items; trackBy: byId">{{ item.name }}</li>
</ul>
<p ngIf="!items.length">Nothing here.</p>
Show answer
<ul>
@for (item of items; track item.id) {
<li>{{ item.name }}</li>
}
</ul>
@if (!items.length) {
<p>Nothing here.</p>
}
Alternatively, put the "Nothing here." text in an @empty block attached to the @for. The byId method on the class is no longer needed.