Sub topic 8
Handling empty collections with @empty
An @for block draws nothing when its collection has no items, which leaves a blank area on the page. The @empty block lets you put a message, an illustration, or a call to action in that space. This chapter covers when @empty renders, what it can and cannot see, and how to combine it with loading and error states.
This chapter assumes you know basic TypeScript, Angular components and templates, and the @for syntax with track from the previous chapters. Familiarity with signals helps, because the examples use them.
What @empty is
@empty is an optional block attached to an @for block. It must follow the closing brace of @for on the same statement, written as } @empty {. Angular renders its content only when the collection has nothing to iterate.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-board',
template: `
<button (click)="add()">Add task</button>
<button (click)="clear()">Clear all</button>
<ul>
@for (task of tasks(); track task.id) {
<li>
{{ task.title }}
<button (click)="remove(task.id)">Remove</button>
</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
`,
})
export class TaskBoardComponent {
private nextId = 1;
tasks = signal<Task[]>([]);
add() {
const id = this.nextId++;
this.tasks.update((list) => [...list, { id, title: `Task ${id}` }]);
}
remove(id: number) {
this.tasks.update((list) => list.filter((t) => t.id !== id));
}
clear() {
this.tasks.set([]);
}
}The component starts empty, so the page shows "No tasks yet." Clicking "Add task" destroys the @empty content and renders the first <li>. Removing the last task brings the @empty content back. Angular creates and destroys these views as the collection changes. It does not hide them with CSS.
When @empty renders
The rule is simple: @empty renders when the @for produces zero iterations. The details matter in a few cases.
| Collection value | `@for` iterations | `@empty` renders |
|---|---|---|
| `[]` | 0 | Yes |
| `[a, b]` | 2 | No |
| `null` or `undefined` | 0 | Yes |
| An empty `Set` or `Map` | 0 | Yes |
| A non-empty iterable | 1 or more | No |
@for accepts any iterable, not only arrays, so @empty works with sets, maps, and generators. A null or undefined collection is treated as empty instead of throwing an error. This is convenient, but it can hide a bug. If a service returns undefined because of a typo in a property name, the user sees "No tasks yet." instead of an error.
import { Component } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-list',
template: `
@for (user of users; track user.id) {
<p>{{ user.name }}</p>
} @empty {
<p>No users to show.</p>
}
`,
})
export class UserListComponent {
users: User[] | null = null; // renders the @empty content
}What is in scope inside @empty
The @empty block runs when no iteration happened, so there is no current item. The loop variable (task above) and the implicit variables ($index, $count, $first, $last, $even, $odd) are not available inside it. Referencing them is a template compile error. Everything else in the component is available: signals, methods, other bindings, child components, and any variables from an enclosing block.
You can put anything in @empty, including components and further control flow:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-inbox',
template: `
@for (mail of messages(); track mail.id) {
<article>{{ mail.subject }}</article>
} @empty {
<section>
<h2>Your inbox is empty</h2>
@if (canCompose()) {
<button (click)="compose()">Write a message</button>
}
</section>
}
`,
})
export class InboxComponent {
messages = signal<{ id: number; subject: string }[]>([]);
canCompose = signal(true);
compose() {
this.messages.update((list) => [
...list,
{ id: list.length + 1, subject: 'Hello' },
]);
}
}A @for block can have only one @empty block, and it must be the last part of the statement. @for has no @else, so @empty is its only fallback.
Why not just use @if?
Before @empty existed, you would write an @if to check the length and put the list inside it:
@if (tasks().length === 0) {
<p>No tasks yet.</p>
} @else {
@for (task of tasks(); track task.id) {
<p>{{ task.title }}</p>
}
}This works, but @empty has some advantages:
- The empty state sits directly next to the loop it belongs to, so a reader sees both at once.
- You do not need an extra nesting level or a
lengthcheck. - It works for iterables that have no
lengthproperty, such as aSet(which hassize) or a generator. - It handles
nullandundefinedwithout extra checks.
Use @if instead when the empty case needs different surrounding markup. For example, the list is wrapped in a <table> with a header row, and the empty state should replace the whole table, not sit in a table cell.
Showing empty results after filtering
A common use is a search box. The list is not empty at the source, but the filtered list is. Compute the filtered list with a computed signal and loop over that.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-fruit-search',
template: `
<input #q type="search" placeholder="Search fruit" (input)="query.set(q.value)" />
<ul>
@for (fruit of visible(); track fruit) {
<li>{{ fruit }}</li>
} @empty {
<li>No fruit matches "{{ query() }}".</li>
}
</ul>
`,
})
export class FruitSearchComponent {
private all = ['apple', 'banana', 'cherry', 'grape'];
query = signal('');
visible = computed(() => {
const term = this.query().toLowerCase();
return this.all.filter((f) => f.includes(term));
});
}Typing "zz" produces an empty visible(), and the @empty block reports the query back to the user. Because the message reads query(), it updates as the user types.
Here track fruit uses the string itself, which is safe only because the values are unique. If two items could share a value, track a unique id instead.
Empty is not the same as loading
The most common mistake with @empty is showing it before the data has arrived. An initial value of [] is empty, so the user sees "No tasks yet." for a moment and then the real list appears. The flash is misleading, and on a slow network it can last seconds.
Keep a separate state for loading and failure, and only reach the @for when the data is known.
import { Component, signal } from '@angular/core';
interface Product {
id: number;
name: string;
}
@Component({
selector: 'app-products',
template: `
@if (loading()) {
<p>Loading products...</p>
} @else if (error()) {
<p>Could not load products.</p>
} @else {
<ul>
@for (p of products(); track p.id) {
<li>{{ p.name }}</li>
} @empty {
<li>No products in this category.</li>
}
</ul>
}
`,
})
export class ProductsComponent {
loading = signal(true);
error = signal(false);
products = signal<Product[]>([]);
constructor() {
setTimeout(() => {
this.products.set([{ id: 1, name: 'Notebook' }]);
this.loading.set(false);
}, 1000);
}
}The three states are now separate, and @empty means exactly "the load succeeded and there is nothing to show". Setting products to [] in the timeout would show the empty message, which is the correct result.
If your data comes from an observable, the as alias from the @if chapter keeps the subscription single and gives you a non-null value:
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-tag-list',
imports: [AsyncPipe],
template: `
@if (tags$ | async; as tags) {
@for (tag of tags; track tag) {
<span>{{ tag }}</span>
} @empty {
<span>No tags.</span>
}
} @else {
<span>Loading tags...</span>
}
`,
})
export class TagListComponent {
tags$: Observable<string[]> = of([]);
}There is a subtle point here. An empty array is truthy in JavaScript, so @if (tags$ | async; as tags) enters the first branch when the array is []. The @else runs only while the observable has not emitted yet (the pipe returns null). That is the behavior you want, and it lets @empty handle the genuinely empty case.
The decision flow
Common mistakes
- Using loop variables in
@empty.$index,$count, and the item variable do not exist there. Read from component state instead. - Confusing empty with not-yet-loaded. Model loading as its own state, as in the products example.
- Hiding errors behind
nullhandling. Becausenullandundefinedrender@empty, a failed request that leaves the field unset looks like "no data". Track errors explicitly. - Forgetting that
@emptyneeds@for. The block is not a general "falsy" check. For a single value that might be missing, use@ifwith@else. - Putting
@emptyin the wrong place. It must come right after the closing brace of the@forblock, not inside it and not after other content.
Exercises
Exercise
A component declares orders = signal<Order[]>([]) and fetches data from an API in ngOnInit. The template is @for (o of orders(); track o.id) { ... } @empty { <p>No orders.</p> }. Users report that "No orders." flashes briefly on every page load, even for accounts with many orders. What causes this, and how do you fix it?
Show answer
The signal starts as [], so @for has zero iterations and @empty renders until the response arrives. Add a separate loading signal (and ideally an error signal), wrap the @for in @if (loading()) { ... } @else { ... }, and set loading to false when the data arrives. @empty then renders only after a successful load that returned no orders.
Exercise
Why does this template fail to compile, and how would you change it? @for (item of items(); track item.id) { <li>{{ item.name }}</li> } @empty { <li>Showing {{ $count }} items</li> }
Show answer
$count is an implicit variable of an iteration, and @empty renders when there are no iterations, so it is not in scope. Since the collection is empty, the number is known to be zero. Either write a fixed message such as "No items", or read the length from component state, for example {{ items().length }}.
Exercise
A Set<string> named selected is passed to @for (s of selected; track s) { ... } @empty { ... }. Does @empty work, and why would an @if (selected.length === 0) check be wrong here?
Show answer
Yes, @for accepts any iterable, and @empty renders when the iteration yields nothing, so an empty Set shows the @empty content. A Set has no length property (it has size), so selected.length === 0 would compare undefined to 0 and always be false, and the empty message would never appear.