Sub topic 1
Why Signals: Fine-Grained Reactivity in Angular
Prerequisites
This chapter assumes you know TypeScript generics and arrow functions, and that you can build Angular components with templates and data binding. You should also have a basic idea of how Angular change detection works.
Why Signals
A signal is a wrapper around a value that tells Angular when the value changes. When code reads a signal, Angular records that code as a consumer of the signal. When the signal changes, Angular notifies only those consumers. This is fine-grained reactivity. Angular no longer has to check the whole component tree after every event. It knows exactly which templates and derived values depend on the changed state.
Creating and Updating Writable Signals
You create a writable signal with signal(initialValue) and read it by calling it as a function. set() replaces the value. update() computes the new value from the current one.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ count() }} (double: {{ double() }})</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`,
})
export class CounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
increment() {
this.count.update(c => c + 1);
}
reset() {
this.count.set(0);
}
}Deriving State with computed()
computed() creates a read-only signal from other signals. It is lazy, so it runs only when something reads it. It is also memoized, so it caches its result and recomputes only after one of its dependencies changes. You cannot call set() on a computed signal.
Running Side Effects with effect()
An effect runs code whenever the signals it reads change. Use effects for work outside Angular's rendering, such as writing to localStorage or logging. Create an effect in an injection context, for example the constructor. Angular then destroys it together with the component. If the effect sets up timers or subscriptions, its callback receives an onCleanup function for releasing them.
import { Component, effect, signal } from '@angular/core';
@Component({
selector: 'app-theme',
template: `<button (click)="toggle()">Theme: {{ theme() }}</button>`,
})
export class ThemeComponent {
theme = signal<'light' | 'dark'>('light');
constructor() {
effect(() => {
localStorage.setItem('theme', this.theme());
});
}
toggle() {
this.theme.update(t => (t === 'light' ? 'dark' : 'light'));
}
}Don't use effects to copy one signal into another. Use computed() for that.
Exercise
In CounterComponent, how many times does the function passed to computed() run if count is updated three times but nothing reads double()?
Show answer
Zero times. computed() is lazy, so it runs only when double() is read, and then once per change in its dependencies.