Built-in Native Control Flow: @if, @for, and @switch
Native Control Flow: Swap clunky structural directives (*ngIf, *ngFor) for clean, intuitive @if, @for (with mandatory tracking), and @switch blocks.
For nearly a decade, Angular managed template branching using asterisk-prefixed structural directives (*ngIf, *ngFor, *ngSwitch). While functional, they carried plenty of baggage:
- Awkward wrapper tags (<ng-container>) just to conditionally show multiple elements.
- Detached fallback blocks (<ng-template #elseBlock>) that fractured template readability.
- Silent performance degradation when developers skipped trackBy.
- The need to import CommonModule across every component.
Modern Angular replaces these runtime directive workarounds with built-in native control flow. Syntactically modeled after JavaScript blocks, @if, @for, and @switch compile straight into the framework's core runtime.
## 1. Structural Directives vs. Native Control Flow
| Dimension | Legacy Directives (*ngIf, *ngFor) | Modern Native Control Flow (@if, @for) |
| --- | --- | --- |
| Imports | Must import CommonModule or individual directives | Zero imports (built directly into the template engine) |
| Branching | Fractured <ng-template #elseBlock> references | Intuitive, inline @else if and @else blocks |
| List Performance | trackBy was optional; omitting it triggered full DOM thrashing | Mandatory track; prevents silent rendering bottlenecks |
| Empty Collections | Required a separate, adjacent *ngIf="items.length === 0" | Dedicated @empty block built into @for |
| Type Narrowing | Inconsistent across nested <ng-template> contexts | Native, automatic TypeScript type narrowing |
| Under the Hood | Emits dynamic <ng-template> runtime views | Compiles down to optimized, native JS control structures |
## 2. Branching Logic: @if, @else if, and @else
### 2.1 Side-by-Side Comparison
```html
```
```html
@if (userRole === 'admin') {
} @else if (userRole === 'editor') {
} @else {
}
```
### 2.2 Aliasing Expressions (Observables and Signals)
Unwrapping async data no longer requires defensive *ngIf hacks. You can alias the resolved value directly within the expression:
```html
@if (currentUser$ | async; as user) {
} @else {
}
```
### 2.3 Automatic Type Narrowing
Because control blocks are evaluated by the template type checker rather than abstracted through directive inputs, TypeScript narrows discriminated unions cleanly:
```ts
type ViewState =
| { state: 'loading' }
| { state: 'success'; payload: string[] }
| { state: 'error'; message: string };
```
```html
@if (status.state === 'success') {
}
```
### What should you pass to track?
- **Unique IDs (Best):** track user.id, track item.uuid
- **Object Reference:** track item (ideal when memory references remain stable)
- **Loop Index (Fallback):** track $index (acceptable only for static, immutable lists)
### 3.2 Contextual Loop Variables
Implicit loop variables are accessible out of the box, prefixed with $:
| Variable | Type | Description |
| --- | --- | --- |
| $index | number | Index of the current iteration (0-indexed) |
| $first | boolean | true if this is the first item |
| $last | boolean | true if this is the last item |
| $even | boolean | true if the current index is even |
| $odd | boolean | true if the current index is odd |
| $count | number | Total number of items in the iterable |
You can use them directly or alias them cleanly:
```html
@for (product of products(); track product.id; let idx = $index, isLast = $last) {
}
```
## 4. Multi-Branch Switching: @switch and @case
Legacy [ngSwitch] required juggling a property binding with nested structural directives (*ngSwitchCase, *ngSwitchDefault).
Native @switch mirrors JavaScript's native switch statement:
```html
@switch (orderStatus()) {
@case ('pending') {
Payment Pending
}
@case ('shipped') {
In Transit
}
@case ('delivered') {
Delivered
}
@default {
Unknown Status
}
}
```
## 5. Scoped Template Variables: The @let Declaration
Historically, caching an expensive calculation or an unwrapped observable forced developers into the hacky <ng-container *ngIf="expr as val"> pattern.
Modern Angular introduces @let, letting you declare reactive, locally-scoped template constants:
```html
@let cart = cart$ | async;
@let tax = calculateTax(cart?.total ?? 0);
@if (cart) {
Grand Total: {{ (cart.total + tax) | currency }}
}
```
- **Block-Scoped:** A variable declared inside an @if or @for block is only visible within that block.
- **Read-Only:** Variables declared with @let are immutable assignments; they recalculate automatically when source signals or observables emit new values.
## 6. Automated Migration
You don't need to manually rewrite legacy templates. The Angular CLI provides a reliable schematic to convert an entire codebase:
```bash
ng generate @angular/core:control-flow
```
What the schematic handles:
- Rewrites *ngIf trees into @if, @else if, and @else.
- Converts *ngFor to @for (and prompts for a fallback tracking policy if track functions were missing).
- Transitions [ngSwitch] into @switch blocks.
- Strips unused CommonModule, NgIf, NgFor, and NgSwitch imports from your components.
- Template Syntax Cheatsheet
```html
@if (isLoggedIn()) {
} @else if (isGuest()) {
} @else {
}
@for (item of items(); track item.id; let i = $index) {
Welcome back, {{ user.name }}
{{ user.tier }}Loaded items: {{ status.payload.length }}
} @else if (status.state === 'error') {{{ status.message }}
} ``` ## 3. Iteration: @for with Enforced Tracking ### 3.1 The End of the trackBy Footgun With *ngFor, tracking was optional. Whenever developers omitted trackBy, Angular couldn't tell which items moved or stayed put during an array update. It simply tore down and rebuilt the entire DOM subtree. Native @for makes tracking compulsory. If you omit the track expression, your template will fail to compile. ```html @for (user of userList(); track user.id) {{{ user.name }}
{{ user.email }}
#{{ idx + 1 }}
}
```
### 3.3 The Dedicated @empty State
Say goodbye to chaining redundant conditional checks underneath an iteration block:
```html
@for (order of orders(); track order.id) {
{{ product.title }}
In catalog: {{ $count }}
Order #{{ order.id }}
{{ order.total | currency }}
} @empty {
No orders found. Start shopping today!
Subtotal: {{ cart.total | currency }}
Estimated Tax: {{ tax | currency }}
Grand Total: {{ (cart.total + tax) | currency }}
{{ i }}: {{ item.title }}
} @empty {
No records available.
}
@switch (priority()) {
@case ('high') { Urgent }
@case ('medium') { Normal }
@default { Low }
}
@let total = subtotal() + tax();
```