Sub topic 7
Conditionals and Lists with @if, @for, and @switch
This chapter assumes you can write a standalone component, read signals in a template with count(), and use event bindings. Angular's built-in control flow blocks let a template add, remove, and repeat elements depending on component state. You don't import anything to use them, because they are part of the template syntax.
@if, @else if, and @else
An @if block renders its content only while its condition is truthy. When the condition becomes falsy, Angular removes the elements from the DOM. Hiding them with CSS would leave them in place.
import { Component, signal } from '@angular/core';
interface User {
name: string;
role: 'admin' | 'editor' | 'viewer';
}
@Component({
selector: 'app-status',
template: `
@if (loading()) {
<p>Loading...</p>
} @else if (user(); as u) {
<p>Welcome, {{ u.name }}</p>
} @else {
<p>Please sign in.</p>
}
<button (click)="loading.set(!loading())">Toggle loading</button>
`
})
export class StatusComponent {
loading = signal(false);
user = signal<User | null>({ name: 'Ada', role: 'admin' });
}The as u clause stores the condition's result in a local variable. That way you read the signal once, and TypeScript narrows u to a non-null User inside the block.
@for with track and @empty
@for repeats its content once for each item in an iterable. It requires a track expression, and the template fails to compile without one. Angular uses the tracked value to match DOM nodes to items across updates, so it can move existing nodes instead of destroying and recreating them.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-task-list',
template: `
<ol>
@for (task of tasks(); track task.id; let i = $index, last = $last) {
<li [class.final]="last">{{ i + 1 }}. {{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}
</ol>
<button (click)="tasks.set([])">Clear</button>
`,
styles: `.final { font-weight: bold; }`
})
export class TaskListComponent {
tasks = signal([
{ id: 1, title: 'Write tests' },
{ id: 2, title: 'Fix bug' }
]);
}@empty renders when the collection has no items. These implicit variables are available inside the loop and can be renamed with let:
| Variable | Meaning |
|---|---|
| `$index` | Position of the current item |
| `$count` | Number of items |
| `$first`, `$last` | Whether the item is first or last |
| `$even`, `$odd` | Whether the index is even or odd |
@switch, @case, and @default
@switch compares one value against each @case using === and renders only the first match. Cases don't fall through, so you don't write break. @default renders when no case matches.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-role-badge',
template: `
@switch (role()) {
@case ('admin') { <span>Administrator</span> }
@case ('editor') { <span>Editor</span> }
@default { <span>Read-only</span> }
}
`
})
export class RoleBadgeComponent {
role = signal<'admin' | 'editor' | 'viewer'>('editor');
}Common errors
- Leaving out
trackin@forcauses a compile error. - Writing
@if (user)whenuseris a signal tests the signal function itself, and a function is always truthy. Call it:@if (user()). - Comparing against the wrong type in
@case, such as@case (1)when the value is'1', never matches, because the comparison uses===.
Exercise
A list of messages is shown with @for (msg of messages(); track $index). New messages are inserted at the top, and each row has a text input. Users report that typed text jumps to a different message. Why, and how do you fix it?
Show answer
When Angular tracks by $index, it matches DOM nodes to items by position. Inserting at the top shifts every item to a new index, so the existing input nodes, along with the text typed into them, now sit next to different messages. Track a stable unique key instead, for example track msg.id. Angular then moves each existing node along with its item.
Exercise
Write an @if block that shows "Out of stock" when stock() is 0, "Low stock" when it is below 5, and otherwise "In stock".
Show answer
@if (stock() === 0) { <p>Out of stock</p> } @else if (stock() < 5) { <p>Low stock</p> } @else { <p>In stock</p> }