Sub topic 7
Rendering every state in the template
This chapter assumes you can create a resource with params and a loader, and that you know Angular control flow (@if, @else). Here you will turn the resource's state signals into a template that handles every case.
The states a template must cover
A resource is never just "data". At any moment it is in one of several statuses, and each one needs a decision about what to show.
| Status | Meaning | `value()` |
|---|---|---|
| `idle` | No request yet because `params` returned `undefined` | `undefined` or the default |
| `loading` | First load, or a reload after `params` changed | `undefined` or the default |
| `reloading` | `reload()` is running | Previous value |
| `resolved` | The loader finished | Loaded value |
| `error` | The loader threw | Not safe to read |
| `local` | `set()` or `update()` changed the value | Local value |
Mapping signals to template branches
You rarely need to compare against status strings. Four signals cover most templates:
error()holds the thrown error, orundefined.isLoading()istruefor bothloadingandreloading.hasValue()istruewhen a value is available. It is a type guard, so inside the branchvalue()is notundefined.value()holds the data.
Check error() first. In recent Angular versions, reading value() while the resource is in the error state throws, so the error branch must come before any branch that reads the value.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-card',
template: `
<button (click)="next()">Next user</button>
@if (user.error()) {
<p>Could not load the user.</p>
<button (click)="user.reload()">Retry</button>
} @else if (user.hasValue()) {
<p [class.stale]="user.isLoading()">{{ user.value().name }}</p>
@if (user.isLoading()) {
<small>Refreshing...</small>
}
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else {
<p>Nothing to show yet.</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;
},
});
next() {
this.userId.update((id) => id + 1);
}
}The branch order is deliberate:
- Error first, so
value()is never read in a failed state. - Value second. During
reloadingthe old value is still present, so the user sees existing data with a small "Refreshing..." hint instead of a blank screen. - Loading third. This branch only appears when there is no value yet.
- The final
@elsecoversidle.
Common mistakes
- Using
isLoading()as the first branch. During a reload it hides data you could still show. - Reading
value()before checkingerror(), which can throw. - Forgetting the idle case. A resource whose
paramsreturnsundefinedis neither loading nor failed, and it shows nothing unless you handle it. - Assuming the old value survives a
paramschange. A newparamsresult starts aloadingstatus, and the previous value is dropped. Onlyreload()keeps it.
Exercise
A template shows a spinner whenever isLoading() is true and the list otherwise. After the user clicks a "Refresh" button that calls reload(), the list disappears and the spinner replaces it. Why, and how do you keep the list visible?
Show answer
isLoading() is also true during the reloading status, so the spinner branch wins even though the previous value is still available. Put a hasValue() branch before the loading branch, so the list renders during a reload, and show a small refresh indicator inside it using isLoading().