Sub topic 7
Rendering every state in the template
This chapter assumes you can write a component with a resource() and a reactive params function, as in the earlier chapters. A resource has more than two states. If the template handles only "loading" and "done", users will see blank screens, stale data under a spinner, or an error that never appears. This chapter walks through how to render each state on purpose.
The states a template must handle
A resource exposes its state through signals. The ones you use in templates are:
value(): the current data, orundefinedif there is none.status(): one of six string values, listed below.error(): the thrown error, orundefined.isLoading():truewhile the status isloadingorreloading.hasValue():truewhen there is usable data. It also narrows the type ofvalue()to excludeundefined.
The status() signal reports one of six values.
| Status | Meaning | `value()` |
|---|---|---|
| `idle` | `params` returned `undefined`, so no request has run. | `undefined` (or `defaultValue`) |
| `loading` | The first load, or a load after `params` changed. | `undefined` (or `defaultValue`) |
| `reloading` | `reload()` is running. | The previous value |
| `resolved` | The loader finished successfully. | The loaded data |
| `error` | The loader threw or rejected. | Not usable |
| `local` | `set()` or `update()` changed the value locally. | The local value |
Here is how a resource moves between these states.
Two details in the diagram matter for templates. A change to params goes to loading, which clears the value. A call to reload() goes to reloading, which keeps the old value on screen.
A first complete template
The simplest correct template checks the error first, then the loading state, then the value.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-card',
template: `
<button (click)="userId.set(userId() + 1)">Next user</button>
@if (user.error()) {
<p role="alert">Could not load the user.</p>
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else if (user.hasValue()) {
<p>{{ user.value().name }}</p>
} @else {
<p>No user selected.</p>
}
`,
})
export class UserCardComponent {
readonly userId = signal(1);
readonly user = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as User;
},
});
}The order of the branches is deliberate:
- Error first. In recent Angular versions, reading
value()while the resource is in theerrorstate can throw. Checkingerror()first means you never readvalue()in that state. - Loading second. This covers
loadingandreloading. - Value third.
hasValue()narrows the type, souser.value().nameneeds no?.. - A final fallback. This catches
idle, where nothing was requested yet.
Do not leave out the last @else. A resource whose params returns undefined is idle. It is neither loading nor failed, and it has no value, so a template without a fallback renders nothing.
Loading versus reloading
isLoading() is true in both loading and reloading. That is usually fine on first load. It causes a visible flicker after reload(), because the old data disappears behind a spinner even though it is still available.
To keep stale data on screen while a reload runs, test hasValue() before isLoading() and show the loading indicator alongside the data.
import { Component, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo-list',
template: `
<button (click)="todos.reload()" [disabled]="todos.isLoading()">Refresh</button>
@if (todos.error()) {
<p role="alert">Could not load todos.</p>
}
@if (todos.hasValue()) {
@if (todos.isLoading()) {
<p>Updating...</p>
}
<ul>
@for (todo of todos.value(); track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li>Nothing to do.</li>
}
</ul>
} @else if (todos.isLoading()) {
<p>Loading...</p>
}
`,
})
export class TodoListComponent {
readonly todos = resource({
loader: async ({ abortSignal }) => {
const res = await fetch('/api/todos', { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
}This template has two independent blocks. The error message appears on its own, so the user can see a failure and still see the last good list, if the resource has one. Whether hasValue() is true after a failed reload depends on the Angular version, so check it in the version you ship.
Switching on status
When you need different markup for each state, @switch on status() reads more clearly than a chain of @else if blocks.
import { Component, resource, signal } from '@angular/core';
interface Product {
id: number;
name: string;
}
@Component({
selector: 'app-product',
template: `
@switch (product.status()) {
@case ('idle') {
<p>Pick a product.</p>
}
@case ('loading') {
<p>Loading product...</p>
}
@case ('reloading') {
<p>Refreshing {{ product.value()?.name }}...</p>
}
@case ('resolved') {
<p>{{ product.value()?.name }}</p>
}
@case ('local') {
<p>{{ product.value()?.name }} (edited, not saved)</p>
}
@case ('error') {
<p role="alert">Failed: {{ message() }}</p>
}
}
`,
})
export class ProductComponent {
readonly productId = signal<number | undefined>(undefined);
readonly product = resource({
params: () => {
const id = this.productId();
return id === undefined ? undefined : { id };
},
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/products/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Product;
},
});
message(): string {
const err = this.product.error();
return err instanceof Error ? err.message : 'Unknown error';
}
}Inside @case blocks the compiler does not narrow value(), so the code uses ?.. The switch also forces you to decide what each of the six statuses looks like. That is a useful check when you review the component.
The local status needs a decision of its own. It means the value no longer matches what the server returned. Whether you show a hint such as "edited, not saved" is a product choice, but you should make it deliberately.
Choosing a `defaultValue`
If a component always needs a list, you can pass defaultValue so value() is never undefined.
import { resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
export const todos = (load: (signal: AbortSignal) => Promise<Todo[]>) =>
resource({
defaultValue: [] as Todo[],
loader: ({ abortSignal }) => load(abortSignal),
});With a default, todos.value().length is safe in any state, and you can drop hasValue() checks for simple cases. The cost is that an empty list now has two meanings: "nothing loaded yet" and "the server returned nothing". If the template must tell these apart, such as showing "No todos yet" only after a successful load, check status() === 'resolved' before you render the empty message.
Common mistakes
- Reading
value()before checkingerror(). In versions wherevalue()throws in the error state, this crashes change detection for the component. - Using
isLoading()as the only gate. The template flickers on everyreload()and shows nothing when the resource is idle. - Treating
idleas an error. An idle resource is waiting for itsparams. This is expected in dependent resources. - Rendering
error()directly. The value is typedunknown, so interpolating{{ user.error() }}showsError: HTTP 404or[object Object], depending on what was thrown. Convert it to a message in the component, asmessage()does above.
Summary of the rules
- Check
error()before you readvalue(). - Use
hasValue()to show data and to narrow its type. - Use
isLoading()for spinners, and remember it includesreloading. - Always handle
idlewith a fallback branch. - Use
@switchonstatus()when each state needs distinct markup. - Convert
error()to a readable message before rendering it.
Exercise
A template reads @if (user.isLoading()) { <p>Loading...</p> } @else { <p>{{ user.value()?.name }}</p> }. List two situations in which it shows something misleading, and say how you would fix each.
Show answer
First, when params returns undefined the resource is idle, so isLoading() is false and the template shows an empty paragraph as if a user had loaded. Add a fallback branch for the idle case, for example @else if (user.hasValue()) followed by a final @else with a prompt. Second, when the loader fails, the status is error, so the template either shows nothing useful or reads value() in a state where it may throw. Add an @if (user.error()) branch before the loading check. A third issue is that reload() sets isLoading() to true and hides the old name behind "Loading...". To keep it visible, test hasValue() first and show a small "Updating..." note next to the data.
Exercise
You use defaultValue: [] on a todo resource. How can the template still show "No todos yet" only after a successful load, and not while the first request is running?
Show answer
Check the status as well as the length. For example, @if (todos.status() === 'resolved' && todos.value().length === 0) { <p>No todos yet</p> }. While the first request runs the status is loading, so the message stays hidden, even though value() is already an empty array.