Sub topic 1
Computed Signals and Effects in Angular: Writable Signals
Prerequisites
You should know basic TypeScript, Angular components and templates, dependency injection, and the general idea of change detection. This chapter assumes you have seen Angular writable signals.
Recap: writable signals
A writable signal stores a value that can change. Create one with signal(). Read its current value by calling it like a function. Change it with set() or derive a new value from the old one with update().
import { signal } from '@angular/core';
const count = signal(0);
console.log(count()); // 0
count.set(5);
count.update((current) => current + 1);
console.log(count()); // 6Angular tracks signal reads in templates and reactive APIs. When count changes, Angular knows which consumers may need to be checked again.
Deriving state with `computed()`
A computed signal is read-only state calculated from other signals. Pass a function to computed(). The function reads its input signals and returns the derived value.
import { signal, computed } from '@angular/core';
const price = signal(10);
const quantity = signal(2);
const total = computed(() => price() * quantity());
console.log(total()); // 20
quantity.set(3);
console.log(total()); // 30The computed signal does not store an independently editable total. It describes a relationship: total is always based on the latest price and quantity.
Use computed() for values such as filtered lists, totals, labels, and validation results. Keep the source data writable and the derived data read-only.
Why computed values are lazy and cached
Computed signals are lazy. Angular does not run the calculation until code reads the computed signal. They are also memoized, which means Angular caches the last result. Repeated reads return the cached result until a dependency changes.
When price or quantity changes, Angular marks total as stale. The next total() read runs the calculation again and stores the new result.
Exercise
What happens when quantity.set(3) runs before total() is read?
Show answer
Angular marks total as stale, but it calculates the new value only when total() is read.