Video lecture
Watch on YouTube(opens in a new tab)Sub topic 10
Conditionals and Lists with @if and @for
This chapter assumes you can create a standalone component and use interpolation ({{ }}) and event binding ((click)) in its template, as covered in the earlier chapters. It shows how to show, hide and repeat parts of a template with Angular's built-in control flow blocks.
The working model
A control flow block starts with @, takes an expression in parentheses, and wraps its content in braces. These blocks are part of the template syntax, so you don't import anything to use them. They replaced the older *ngIf and *ngFor directives, which needed NgIf and NgFor imports.
| Block | Purpose |
|---|---|
| `@if` / `@else if` / `@else` | Render one branch based on a condition |
| `@for` / `@empty` | Repeat content for each item, with a fallback for an empty collection |
| `@switch` / `@case` / `@default` | Pick one branch by matching a value |
Angular evaluates the conditions in order and renders only the first branch that matches. Branches that don't match are removed from the DOM, not just hidden with CSS.
A worked example
import { Component } from '@angular/core';
interface Task {
id: number;
title: string;
done: boolean;
}
@Component({
selector: 'app-task-board',
template: `
@if (loading) {
<p>Loading...</p>
} @else if (tasks.length === 0) {
<p>No tasks yet.</p>
} @else {
<ul>
@for (task of tasks; track task.id; let i = $index, last = $last) {
<li>
{{ i + 1 }}. {{ task.title }}
@if (task.done) { <strong>(done)</strong> }
@if (last) { <em>- end of list</em> }
</li>
}
</ul>
}
<button (click)="loading = !loading">Toggle loading</button>
<button (click)="tasks = []">Clear tasks</button>
`,
})
export class TaskBoard {
loading = false;
tasks: Task[] = [
{ id: 1, title: 'Install the CLI', done: true },
{ id: 2, title: 'Create a project', done: false },
];
}Inside @for you can alias the built-in context variables: $index, $first, $last, $even, $odd and $count. To render fallback content for an empty list, you can attach @empty directly to the loop instead of writing a separate @if:
@for (task of tasks; track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}Why `track` is required
track tells Angular how to identify each item, so that when the array changes it can reuse the existing DOM nodes rather than rebuilding them. A @for without track fails to compile. Choose the expression this way:
- Use a stable unique key such as
task.idfor data that comes from a server. - Use
track $indexonly for static lists that are never reordered. - Use
track item(object identity) only if the same object references survive updates. If the data is fetched again, every object is new, so Angular destroys and recreates every row.
Common errors
- Missing
track: the build fails with an error saying@forloop must have a "track" expression. - Literal
@,{or}in text: the template parser reads these characters as syntax. Write them as@,{and}, so an email address like[email protected]becomesme@example.com. - Using
@elsewithout@ifright before it:@elsemust follow the closing brace of an@ifor@else ifblock. - Expecting hidden branches to keep their state: a branch that is removed is destroyed. Any child components inside it, and their state, are recreated when the branch renders again.
Exercise
A list of users is fetched again from an API every 30 seconds. The template uses @for (user of users; track user). Why does every row flicker and lose focus on each refresh, and what should you change?
Show answer
Each refresh creates new user objects, so tracking by object identity treats every item as new, and Angular destroys and recreates all the rows. Track by a stable key instead, for example track user.id.
Exercise
Rewrite @if (items.length) { <ul>@for (i of items; track i.id) {<li>{{ i.name }}</li>}</ul> } @else { <p>Empty</p> } to use @empty, accepting that the fallback renders inside the list.
Show answer
<ul>@for (i of items; track i.id) { <li>{{ i.name }}</li> } @empty { <li>Empty</li> }</ul>