Sub topic 10
Using Signals in Templates
This chapter assumes you know interpolation, property binding, and event binding from earlier chapters. It also assumes you can write TypeScript classes with generics and can run a standalone Angular component (Angular 17 or later, so the built-in @if and @for blocks are available).
Up to now, every binding in this tutorial has read a plain class field such as name = 'Ada'. That works, but Angular has to check every such binding to find out whether anything changed. A signal is a wrapper around a value that tells Angular when the value changes. When a template reads a signal, Angular records that the template depends on it. When the signal changes, Angular knows which view needs updating. This chapter covers how to create signals, read them in templates, derive values with computed(), and avoid the mistakes people make most often.
What a Signal Is
You create a signal with signal(initialValue) from @angular/core. The result is a function. You call it to read the value, and you call its methods to change the value.
| Operation | Syntax | Effect |
|---|---|---|
| Create | `count = signal(0)` | Makes a `WritableSignal<number>` holding `0` |
| Read | `count()` | Returns the current value and records a dependency |
| Replace | `count.set(5)` | Stores a new value and notifies dependents |
| Update from previous | `count.update(c => c + 1)` | Computes the new value from the old one |
| Read-only view | `count.asReadonly()` | Returns a `Signal<number>` with no `set` or `update` |
Reading a signal is a function call. This is the one syntax rule you have to remember: in a template you write count(), not count.
A First Signal in a Template
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-like-button',
template: `
<p>{{ likes() }} people like this</p>
<button (click)="like()" [disabled]="liked()">
{{ liked() ? 'Liked' : 'Like' }}
</button>
`,
})
export class LikeButtonComponent {
likes = signal(12);
liked = signal(false);
like() {
this.likes.update(n => n + 1);
this.liked.set(true);
}
}Each binding form you already know works the same way with signals. Interpolation {{ likes() }}, property binding [disabled]="liked()", and conditional expressions all just call the signal. The event binding (click)="like()" calls an ordinary method, and the method writes to the signals. You can also write to a signal directly in the template, for example (click)="likes.set(0)". Keep that for one-line actions, because longer logic belongs in a method you can test.
Derived State with computed()
You will often need a value that depends on other values, such as a total, a filtered list, or a validity flag. computed() takes a function that reads other signals and returns a read-only signal of the result.
import { Component, computed, signal } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
interface CartItem {
id: number;
name: string;
price: number;
qty: number;
}
@Component({
selector: 'app-cart',
imports: [CurrencyPipe],
template: `
<h2>Cart ({{ itemCount() }} items)</h2>
@for (item of items(); track item.id) {
<div>
{{ item.name }} x {{ item.qty }}
<button (click)="addOne(item.id)">+</button>
</div>
} @empty {
<p>Your cart is empty.</p>
}
<p [class.over-budget]="overBudget()">
Total: {{ total() | currency }}
</p>
<button [disabled]="items().length === 0" (click)="clear()">Clear</button>
`,
styles: `.over-budget { color: crimson; }`,
})
export class CartComponent {
budget = signal(50);
items = signal<CartItem[]>([
{ id: 1, name: 'Notebook', price: 4.5, qty: 2 },
{ id: 2, name: 'Pen', price: 1.25, qty: 4 },
]);
itemCount = computed(() =>
this.items().reduce((sum, i) => sum + i.qty, 0)
);
total = computed(() =>
this.items().reduce((sum, i) => sum + i.price * i.qty, 0)
);
overBudget = computed(() => this.total() > this.budget());
addOne(id: number) {
this.items.update(list =>
list.map(i => (i.id === id ? { ...i, qty: i.qty + 1 } : i))
);
}
clear() {
this.items.set([]);
}
}A computed signal has these properties:
- Lazy. The function does not run until something reads the computed signal.
- Memoized. After it runs, the result is cached. Reading
total()three times in a template runs the reduce once. - Dynamically tracked. Dependencies are whatever signals the function actually read on its last run. If a branch skips reading a signal, changes to that signal do not trigger a recompute.
- Read-only.
total.set(10)is a compile error. To change a derived value, change its sources.
Computed signals can depend on other computed signals. overBudget reads total, which reads items. Angular builds a dependency graph from these reads.
Why Signals Help the Template
With plain fields, Angular cannot tell that this.total changed. It re-evaluates every binding in the component during change detection and compares the old and new results. With signals, the template becomes a consumer of the signals it reads. A write to items marks the components whose templates read it, directly or through a computed signal, as needing a refresh. Angular can then skip the components that do not depend on the change.
This also makes signals work well with ChangeDetectionStrategy.OnPush. An OnPush component normally refreshes only when its inputs change or when an event fires inside it. A signal read in its template is a third trigger, so a signal updated from a timer or a service still refreshes the view. The chapter on change detection covers this mechanism in detail.
Signals Shared Through a Service
Signals don't have to live in the component. A service can own the state and expose a read-only view of it:
import { Component, Injectable, computed, inject, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
private readonly _dark = signal(false);
readonly dark = this._dark.asReadonly();
readonly label = computed(() => (this._dark() ? 'Dark' : 'Light'));
toggle() {
this._dark.update(d => !d);
}
}
@Component({
selector: 'app-theme-toggle',
template: `
<button (click)="theme.toggle()" [class.dark]="theme.dark()">
Theme: {{ theme.label() }}
</button>
`,
})
export class ThemeToggleComponent {
protected readonly theme = inject(ThemeService);
}Every component that reads theme.dark() updates when toggle() runs. No subscription is needed and nothing has to be cleaned up when the component is destroyed. Because the service exposes only asReadonly(), other code can change the theme only through toggle().
Common Errors
Forgetting the parentheses
{{ likes }} does not show 12. It interpolates the signal function itself, so you see a string representation of the function instead of the value. The same mistake in [disabled]="liked" is worse, because a function is always truthy and the button stays disabled. Angular's extended diagnostics report the interpolation case as interpolatedSignalNotInvoked, so pay attention to that warning when you build.
Mutating a value in place
Signals decide whether a value changed using Object.is equality by default. This code does nothing visible:
this.items.update(list => {
list.push({ id: 3, name: 'Ruler', price: 2, qty: 1 });
return list; // same array reference, so no change is reported
});The array really did change, but the reference is the same, so dependents are not notified and total keeps its cached value. Always return a new object or array:
this.items.update(list => [...list, { id: 3, name: 'Ruler', price: 2, qty: 1 }]);Writing to signals inside computed()
A computed() function should only read and return. Calling set inside it produces an error, because a derivation that changes its own inputs can loop forever. If you need a side effect when a signal changes, such as logging or writing to localStorage, use effect(). You do not need effect() just to update the template, because template bindings already track the signals they read.
Expensive work in plain methods
A binding such as {{ formatTotal() }}, where formatTotal is an ordinary method, runs again on every change detection pass. Moving that work into a computed() caches it until its inputs change.
Mixing signals and plain fields
If a template reads count() and also a plain field status, an OnPush component will not refresh when only status changes from outside an event. In a component that uses signals, keep all template-visible state in signals so updates are reliable.
When to Use a Signal
| State | Recommended form |
|---|---|
| Value the template shows and the component changes | `signal()` |
| Value derived from other state | `computed()` |
| Constant that never changes | Plain `readonly` field |
| State shared between components | Signal in a service, exposed with `asReadonly()` |
| Data from a parent component | `input()`, covered in the next chapter |
Exercise
A template contains <p>{{ user.name }}</p> where user = signal({ name: 'Ada' }). What does it display, and how do you fix it?
Show answer
user is a signal function, so user.name reads the function's built-in name property instead of your data and does not show 'Ada'. Call the signal first: {{ user().name }}.
Exercise
A method runs this.tags.update(t => { t.push('new'); return t; }), but the list rendered with @for (tag of tags(); track tag) does not change. Why, and what is the fix?
Show answer
push mutates the existing array and the callback returns the same reference. The signal compares values with Object.is, sees no change, and does not notify the template. Return a new array instead: this.tags.update(t => [...t, 'new']).
Exercise
Add a discount signal (a fraction such as 0.1) to the cart component and show the discounted total without changing total. Which API do you use, and what does the template binding look like?
Show answer
Add discount = signal(0.1) and discountedTotal = computed(() => this.total() * (1 - this.discount())), then bind {{ discountedTotal() | currency }}. The computed signal recalculates only when items or discount changes.