Sub topic 1
Angular Control Flow with @if, @for, and @switch
Prerequisites
Assume you know basic TypeScript, Angular components, templates, interpolation, and event or property binding. Signals are helpful but not required.
Why Angular has built-in control flow
Angular templates now provide control flow blocks directly: @if, @for, and @switch. A control flow block chooses which template content Angular creates or updates.
Older Angular code commonly used structural directives such as *ngIf and *ngFor. Those directives transformed the template and often required imports. Built-in blocks use clearer syntax and support template features such as type narrowing and local aliases directly.
> callout note > Use @if when the template should depend on a condition. Use @for for collections and @switch when one value selects among several known cases.
Showing content conditionally with @if
Place the content inside braces. Angular evaluates the condition and renders the block only when the result is truthy.
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>
}
`,
})
export class SessionComponent {
isLoggedIn = signal(false);
}A signal is a reactive value. Calling isLoggedIn() reads its current value. Calling .set() changes it, which causes Angular to update the dependent template.
Handling alternatives with @else if and @else
An @else if branch tests another condition only when earlier conditions fail. An @else branch handles every remaining case.
@if (status() === 'loading') {
<p>Loading...</p>
} @else if (status() === 'error') {
<p>Something went wrong.</p>
} @else {
<p>Data is ready.</p>
}Branches are mutually exclusive. Angular renders the first matching branch.
Keeping an expression result with as
Use ; as name to store an expression result for the block. This avoids evaluating or subscribing to the same expression repeatedly.
@if (user$ | async; as user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading profile...</p>
}Here, user is available only inside the @if block. When the observable has not produced a value, Angular renders the @else content.
Exercise
Which branch renders when status() returns "error" in the three-branch example?
Show answer
The @else if (status() === 'error') branch renders, and the @if and @else branches do not.