Sub topic 4
Reading Signals in Templates
This chapter assumes you have read the previous chapters on component anatomy and interpolation. You should be comfortable with TypeScript classes, generics, and arrow functions. Event binding gets its own chapter later. Here it appears only as (click)="..." so that values have a way to change.
A signal is a wrapper around a value that tells Angular when the value changes. When a template reads a signal, Angular records that read. When the signal changes later, Angular knows which views need updating. Signals are now the standard way to hold component state, so most of the templates in this tutorial read them.
The Working Model
Creating, reading, and writing a signal
You create a writable signal with signal(initialValue). The result is a getter function. You read the value by calling it, and you change it with set() or update().
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `
<p>Hello, {{ name() }}!</p>
<p>You have visited {{ visits() }} times.</p>
<button (click)="rename()">Rename</button>
<button (click)="visit()">Visit again</button>
`
})
export class GreetingComponent {
name = signal('Ada');
visits = signal(0);
rename() {
this.name.set('Grace');
}
visit() {
this.visits.update(v => v + 1);
}
}| Operation | Syntax | Use when |
|---|---|---|
| Read | `count()` | Anywhere: class code or template |
| Replace | `count.set(5)` | The new value does not depend on the old one |
| Derive from old | `count.update(c => c + 1)` | The new value is computed from the current one |
| Expose read-only | `count.asReadonly()` | Other code may read the signal but must not write it |
TypeScript infers the type from the initial value. Pass the type explicitly when the initial value is narrower than what you will store later, for example signal<string | null>(null).
Why the parentheses matter in the template
{{ name() }} calls the getter. Angular runs that call inside a reactive context, so the call records a dependency between this view and name. A later set() on name marks the view for refresh. You never tell Angular what changed. The read itself carries that information.
Derived State with computed()
A computed() signal derives its value from other signals. Angular tracks every signal read inside the computation function. The function runs lazily, the first time someone reads the result, and Angular caches that result until a dependency changes.
import { Component, computed, signal } from '@angular/core';
interface Item {
name: string;
price: number;
qty: number;
}
@Component({
selector: 'app-cart',
template: `
<ul>
<li>{{ items()[0].name }} × {{ items()[0].qty }}</li>
</ul>
<p>Total: {{ total() }}</p>
<p>{{ summary() }}</p>
<button (click)="addOne()">Add another {{ items()[0].name }}</button>
`
})
export class CartComponent {
items = signal<Item[]>([{ name: 'Pen', price: 2, qty: 1 }]);
total = computed(() =>
this.items().reduce((sum, i) => sum + i.price * i.qty, 0)
);
summary = computed(() =>
this.total() > 10 ? 'Free shipping!' : 'Spend over 10 for free shipping.'
);
addOne() {
this.items.update(list =>
list.map((item, idx) => (idx === 0 ? { ...item, qty: item.qty + 1 } : item))
);
}
}summary depends on total, and total depends on items, so derivations chain together. Computed signals are read-only. They have no set() method.
computed() versus a plain method
You can also derive values with a class method called from the template, as in {{ remaining() }} where remaining() is an ordinary function. That works, and it still picks up signal reads, because the function runs during rendering. The difference is caching.
| Approach | Re-runs when | Cost |
|---|---|---|
| Method called in template | Every time the view is checked | Repeated work on each check |
| `computed()` | Only after a dependency signal changes | Runs once per change, then reads from cache |
For a cheap filter over three items, the difference does not matter. For sorting, filtering large lists, or formatting many values, prefer computed().
Common Errors
Forgetting to call the signal
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-broken',
// Wrong: interpolates the function itself, not its value.
template: `<p>{{ count }}</p>`
})
export class BrokenComponent {
count = signal(0);
}This renders the signal function's string form instead of 0. Angular's extended diagnostics report it as NG8109 ("should be invoked"). The fix is {{ count() }}. The same mistake inside a condition is harder to spot. count is always truthy because it is a function, so a test like count && ... never fails.
Mutating the value in place
Signals compare the old and new values with Object.is. If you mutate an array or object and hand back the same reference, Angular sees no change and the view does not update.
// Wrong: same array reference, no notification.
this.items.update(list => {
list.push({ name: 'Ink', price: 5, qty: 1 });
return list;
});
// Right: new array reference.
this.items.update(list => [...list, { name: 'Ink', price: 5, qty: 1 }]);Writing to a signal inside computed()
A computed function should only read. Calling set() inside it causes an error, and the design is wrong in any case. If a write must happen in reaction to a change, it belongs in an event handler. A later chapter on lifecycle covers the rarer cases that call for effect().
Exposing writable state to callers
A service or parent that hands out a WritableSignal lets any caller change it. Keep the writable signal private and expose asReadonly():
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
private readonly _dark = signal(false);
readonly dark = this._dark.asReadonly();
toggle() {
this._dark.update(d => !d);
}
}Edge Cases Worth Knowing
- Equality for primitives:
count.set(3)when the value is already3does not notify anything. That saves work and is rarely a problem. - Custom equality:
signal(value, { equal: (a, b) => a.id === b.id })suppresses notifications when your rule says two values are the same. Use it carefully. A wrong rule hides real updates. - Reading many times: Calling
items()several times in one template is cheap, because each call just returns the stored value. You do not need to copy it into a local variable for performance. - Non-signal fields: Plain class fields still render, but Angular only notices their changes through zone-based change detection. Mixing the two styles works. Keeping state in signals gives you predictable updates, which the change detection chapter explains in detail.
Exercise
A component has tags = signal<string[]>([]) and a method addTag(t: string) { this.tags().push(t); }. The template shows {{ tags().length }}. Why might the count fail to update, and how do you fix it?
Show answer
this.tags().push(t) mutates the existing array and never calls set or update, so the signal never notifies its dependents. Even update returning the same array would fail the Object.is check. Fix it with this.tags.update(list => [...list, t]);, which stores a new array reference.
Exercise
You have price = signal(20) and qty = signal(3). Write a computed signal subtotal and a second computed signal label that reads "Bulk" when the subtotal is at least 50 and "Standard" otherwise. When does label recompute?
Show answer
subtotal = computed(() => this.price() * this.qty()); and label = computed(() => (this.subtotal() >= 50 ? 'Bulk' : 'Standard'));. label recomputes lazily, on its next read after subtotal changes. subtotal changes only after price or qty changes to a value that gives a different product.
Exercise
A template contains @if (isAdmin) { <p>Admin tools</p> } where isAdmin = signal(false). The admin tools always appear. Explain why.
Show answer
The template refers to isAdmin without calling it. A signal is a function, and a function is truthy, so the condition always passes. Use @if (isAdmin()) { ... }.