Sub topic 11
Nesting and combining blocks
This chapter assumes you know @if, @else if, @else, @for with track, @empty, and @switch from the earlier chapters. It also assumes you can read a signal-based component. Here you will put the blocks together, and you will see which combinations work well and which cause trouble.
Blocks are ordinary template content
The body of a control flow block is a normal template fragment. It can hold elements, text, interpolation, components, and other blocks. Blocks do not render a wrapper element, so you can nest them as deeply as the layout needs without adding extra <div> or <ng-container> tags.
Each block type has clauses that only it accepts:
| Clause | Valid after | Purpose |
|---|---|---|
| `@else if (...)`, `@else` | `@if` | Alternative branches |
| `@empty` | `@for` | Fallback when the collection has no items |
| `@case (...)`, `@default` | inside `@switch` | One branch per value |
@for has no @else, and @if has no @empty. If you need both behaviors, wrap one block in the other.
A worked example: switch, if, and for together
The component below shows a product catalog. An outer @switch handles the request status. The ready case contains an @if and a @for with an @empty fallback. Inside each list item, a small @if marks sold-out products.
import { Component, computed, signal } from '@angular/core';
interface Product {
id: number;
name: string;
inStock: boolean;
}
type Status = 'loading' | 'error' | 'ready';
@Component({
selector: 'app-catalog',
template: `
<button (click)="onlyInStock.set(!onlyInStock())">
Toggle stock filter
</button>
@switch (status()) {
@case ('loading') {
<p>Loading...</p>
}
@case ('error') {
<p>Could not load products.</p>
}
@case ('ready') {
@if (onlyInStock()) {
<p>Showing in-stock items only.</p>
}
<ul>
@for (p of visible(); track p.id) {
<li>
{{ p.name }}
@if (!p.inStock) {
<em>(sold out)</em>
}
</li>
} @empty {
<li>No products match.</li>
}
</ul>
}
}
`,
})
export class CatalogComponent {
status = signal<Status>('ready');
onlyInStock = signal(false);
products = signal<Product[]>([
{ id: 1, name: 'Keyboard', inStock: true },
{ id: 2, name: 'Monitor', inStock: false },
]);
visible = computed(() =>
this.onlyInStock()
? this.products().filter((p) => p.inStock)
: this.products(),
);
}Three points about this design:
- The
@switchis on the outside because the status decides whether the list exists at all. Put the broadest decision at the outermost level. - The
@emptyblock runs only whenvisible()is empty. That is why filtering happens in acomputedsignal, as the next section explains. - None of these blocks needs an import in the component, because built-in control flow is part of the template syntax.
Filtering: use a computed value, not an @if inside @for
A common first attempt at filtering is to put an @if inside the loop:
<ul>
@for (p of products(); track p.id) {
@if (p.inStock) {
<li>{{ p.name }}</li>
}
} @empty {
<li>No products match.</li>
}
</ul>This looks right but has a flaw. @empty checks the collection that @for iterates, not what the inner @if renders. If products() has two items and both are sold out, the loop runs twice, renders nothing, and the empty message never appears. The user sees a blank list.
Filter before the template sees the collection. A computed signal (as in the catalog example) or a method that returns a filtered array keeps @empty accurate. It also keeps filtering logic in TypeScript, where you can test it.
An inner @if is still the right tool when a condition affects part of each item, such as the sold-out marker above.
Nested @for blocks and the outer index
When you nest one @for inside another, each loop has its own implicit variables. The inner $index hides the outer $index, so the inner template cannot see the outer position under that name. Alias the outer value with let and use the alias inside the inner loop.
import { Component, signal } from '@angular/core';
interface Item {
id: number;
label: string;
}
interface Group {
id: number;
title: string;
items: Item[];
}
@Component({
selector: 'app-outline',
template: `
@for (group of groups(); track group.id; let g = $index) {
<h3>{{ g + 1 }}. {{ group.title }}</h3>
<ol>
@for (item of group.items; track item.id; let i = $index) {
<li>{{ g + 1 }}.{{ i + 1 }} {{ item.label }}</li>
} @empty {
<li>No items in this group.</li>
}
</ol>
}
`,
})
export class OutlineComponent {
groups = signal<Group[]>([
{
id: 1,
title: 'Setup',
items: [
{ id: 10, label: 'Install' },
{ id: 11, label: 'Configure' },
],
},
{ id: 2, title: 'Extras', items: [] },
]);
}Each loop needs its own track expression. The inner one tracks item.id, so its uniqueness only has to hold within a single group. The @empty on the inner loop runs per group, so "Extras" shows its own fallback while "Setup" lists its items.
Branches inside @switch cases
A @case body can contain any other block. This is useful when one case is simple and another needs its own conditions or list.
@switch (role()) {
@case ('admin') {
@if (pendingCount() > 0) {
<p>{{ pendingCount() }} requests need review.</p>
} @else {
<p>Nothing to review.</p>
}
}
@case ('editor') {
<p>You can edit drafts.</p>
}
@default {
<p>Read-only access.</p>
}
}Remember that @switch compares with strict equality and does not fall through, so each case is independent. There is no break to write. If several values should share one branch, you have two choices. You can repeat the markup in each @case. Or you can compute a single value first, such as canEdit(), and switch on that.
Choosing between @switch and an @else if chain
Both can express "pick one of several". They suit different shapes of condition.
| Situation | Better choice | Reason |
|---|---|---|
| One expression compared to fixed values | `@switch` | The expression is written once, and the cases read like a list |
| Different conditions per branch | `@else if` chain | Each branch can test something unrelated |
| Range checks such as `count() > 10` | `@else if` chain | `@case` only checks equality |
| You need an alias for the matched value | `@if (...; as name)` | `@switch` has no `as` clause |
A chain of @else if blocks also supports aliases. The alias exists only inside the block that declares it, so it is not visible in a later @else branch.
Combining blocks with ng-container and ng-template
Blocks remove most uses of <ng-container>, but some remain. Use <ng-container> when you need an invisible parent for something that requires an element host, for example a structural directive you still use, or an ngTemplateOutlet.
You can also put blocks inside an <ng-template>. The template is only rendered where you place it, and the blocks inside behave as usual when it renders.
<ng-template #rowTemplate let-row>
@if (row.archived) {
<s>{{ row.title }}</s>
} @else {
{{ row.title }}
}
</ng-template>
@for (row of rows(); track row.id) {
<ng-container *ngTemplateOutlet="rowTemplate; context: { $implicit: row }" />
}This example imports NgTemplateOutlet from @angular/common in the component's imports array, because that directive is not part of control flow.
Mixing old and new syntax
A template can use *ngIf in one place and @if in another. This is useful while you migrate a large project in stages. One old restriction still applies. You cannot put two structural directives on the same element, so *ngIf and *ngFor together on one tag is an error. Blocks avoid the problem, because nesting is explicit:
@for (user of users(); track user.id) {
@if (user.active) {
<app-user-card [user]="user" />
}
}If you find yourself reaching for <ng-container *ngIf> to hold a *ngFor, replace both with nested blocks.
A decision flow for a typical list view
Most data views follow the same order of questions. Ask the broad ones first and the narrow ones last, and the nesting stays shallow.
Keeping nested templates readable
- Limit depth. Past three levels of nesting, move the inner part into a child component with an input. The template becomes shorter, and the child can be tested alone.
- Move logic into TypeScript. Filtering, sorting, and grouping belong in
computedsignals or methods. Templates should only choose what to show. - Alias values you use more than once. Writing
@if (user(); as u)and then usingugives you a stable name. It also lets the template type checker treatuas non-null inside the block, which it does not do for repeated calls likeuser(). - Keep one concern per block. An
@ifthat decides "loading or not" should not also decide "has permission". Nest a second@iffor the second question.
Exercises
Exercise
A template uses @for (t of tasks(); track t.id) { @if (!t.done) { <li>{{ t.title }}</li> } } @empty { <li>All caught up</li> }. All tasks are marked done, yet the user sees an empty list and no message. Why, and how do you fix it?
Show answer
@empty only runs when tasks() itself has no items. Here the loop still iterates over every task, and the inner @if hides each one, so nothing renders and @empty never fires. Create a computed signal such as pending = computed(() => this.tasks().filter(t => !t.done)), iterate over pending(), and keep @empty on that loop.
Exercise
You nest an inner @for over group.items inside an outer @for over groups(). The inner template must print the outer loop position and the inner position, like 2.3. Write the two @for headers.
Show answer
Outer: @for (group of groups(); track group.id; let g = $index). Inner: @for (item of group.items; track item.id; let i = $index). Inside the inner loop, use {{ g + 1 }}.{{ i + 1 }}. The alias g keeps the outer index available, because the inner $index would otherwise hide it.