FresherCodingAngular
Explain computed signals with a small example
Try answering first
Model answer
A computed signal is a read-only value derived from other signals. Angular tracks which signals the function reads and recalculates only when one of them changes.
import { computed, signal } from '@angular/core'
const price = signal(20)
const qty = signal(3)
const total = computed(() => price() * qty())
console.log(total()) // 60
qty.set(5)
console.log(total()) // 100
Three properties matter:
- It is lazy: the function does not run until someone reads
total(). - It is memoized: reading it twice without a change reuses the cached result.
- It is read-only:
total.set(...)does not exist, so the value always follows its sources.
Dependencies are tracked at run time, so a signal read inside an if branch is only a dependency when that branch runs. Use computed for anything you can calculate from other state, such as totals, filtered lists or labels.
Derive with computed instead of storing the same data twice.
Key points
- computed derives a value from other signals
- It is lazy and memoized
- It is read-only
- Dependencies are tracked automatically at run time
Likely follow-ups
- What happens if a computed reads no signals?
Common mistakes
- Trying to call set on a computed signal
- Storing derived data in a separate signal and keeping it in sync by hand