Sub topic 5
Computing values from inputs
A child component often needs a value that depends on its inputs, such as initials from a name or a total from a price and a quantity. This chapter shows how to build those values with computed() so they stay correct when the parent changes the inputs.
This chapter assumes you know TypeScript classes and generics, standalone components, property binding and event binding, and how to read a signal by calling it. It builds on the input() and input.required() functions from the previous chapters.
Why derived state needs a signal
A signal input is a read-only signal. When the parent binds a new value, the signal's value changes, and everything that read the signal is notified. A plain class field that copies an input does not take part in this. It is computed once and never updated.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>{{ message }}</p>`,
})
export class Greeting {
name = input('stranger');
// Wrong: this runs once, when the field is initialized.
message = 'Hello, ' + this.name();
}This component always shows Hello, stranger, because the field initializer runs before the parent has bound anything. The fix is to describe the derived value as a computation that reruns when its dependencies change.
Deriving a value with computed()
computed() takes a function and returns a read-only signal. Angular records which signals the function reads. When any of them changes, the computed value is marked stale and is recalculated the next time something reads it.
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-avatar',
template: `<span class="avatar">{{ initials() }}</span>`,
})
export class Avatar {
name = input.required<string>();
initials = computed(() =>
this.name()
.split(' ')
.map((part) => part[0])
.join('')
);
}If the parent binds [name]="user.name" and user.name changes from Ada Lovelace to Grace Hopper, the name input updates, initials is marked stale, and the template shows GH on the next change detection pass. You never write code to connect the two steps.
You call a computed signal like any other signal: initials(). In the template and in other computed functions, this registers a dependency.
Combining several inputs
A computed function can read as many signals as it needs. The dependencies are tracked from what the function reads each time it runs, so you do not list them.
import { Component, computed, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-line-total',
template: `
<p>{{ quantity() }} x {{ unitPrice().toFixed(2) }}</p>
<p>Total: {{ total().toFixed(2) }}</p>
`,
})
export class LineTotal {
unitPrice = input.required<number>();
quantity = input(1, { transform: numberAttribute });
discount = input(0); // a fraction, for example 0.1 for 10%
total = computed(() => this.unitPrice() * this.quantity() * (1 - this.discount()));
}The parent can use it as <app-line-total [unitPrice]="9.5" quantity="3" [discount]="0.1" />. Changing any one of the three inputs recalculates total. Because quantity uses numberAttribute, the static attribute "3" arrives as the number 3, so the multiplication works. Without the transform the type of quantity would be wrong for that usage, and the type checker would reject the binding.
Chaining computed values
One computed signal can read another. Keep each step small and name it for what it means.
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-progress',
template: `<progress [value]="percent()" max="100"></progress> {{ label() }}`,
})
export class Progress {
done = input(0);
total = input.required<number>();
percent = computed(() =>
this.total() === 0 ? 0 : Math.round((this.done() / this.total()) * 100)
);
label = computed(() => `${this.percent()}% complete`);
}The total() === 0 guard matters. A parent may briefly pass 0 while data loads, and dividing by zero would produce NaN in the template.
Properties of computed signals
These rules explain most surprises you will meet.
| Property | What it means in practice |
|---|---|
| Lazy | The function does not run until something reads the value. An unused computed never runs. |
| Memoized | The result is cached. Reading it again without a dependency change returns the cached value and does not rerun the function. |
| Read-only | There is no `set()` or `update()`. The value can only change through its dependencies. |
| Dynamic dependencies | Only signals read on the latest run count. A signal inside an untaken `if` branch is not tracked until that branch runs. |
| Equality check | If a recalculation gives the same value (compared with `Object.is`), readers are not notified. |
The equality check has a consequence for objects and arrays. If your computed function builds a new array every time, such as items().filter(...), the result is a new reference after each dependency change, so readers are always notified. That is usually what you want. It is wasteful only if the dependency changes often and the filtered content stays the same.
Computed functions should be pure. Do not set other signals, call services that change state, or log from inside them. They may run at times you do not control, and a side effect in them is hard to reason about.
When input values are available
Signal inputs are set by Angular after it creates the component instance. That has two effects.
- In a field initializer or the constructor, an input has no bound value yet. A required input has no value at all, and reading it there throws an error (
NG0950). An optional input returns its initial value. - Inside
computed(), the problem does not appear, because the function is lazy. It first runs when the template reads it, and by then the inputs are bound.
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-title',
template: `<h1>{{ upper() }}</h1>`,
})
export class TitleView {
text = input.required<string>();
// Wrong: runs during construction and throws NG0950.
// upper = this.text().toUpperCase();
// Right: deferred until the template reads it.
upper = computed(() => this.text().toUpperCase());
}An optional input also changes over time. In a field initializer you see the default, and after the first binding you see the parent's value. A computed signal handles both cases without special code, because it reads the current value each time.
Reacting to changes with effect()
computed() is for values. Use effect() when a change must cause an action outside the component's own state, such as writing to localStorage or calling a non-signal API. An effect created in the constructor or as a field initializer runs after the inputs are bound.
import { Component, effect, input } from '@angular/core';
@Component({
selector: 'app-page-title',
template: `<h1>{{ title() }}</h1>`,
})
export class PageTitle {
title = input.required<string>();
constructor() {
effect(() => {
document.title = this.title();
});
}
}Reading this.title() inside the effect is safe even though it sits in the constructor, because the effect body runs later, not during construction. Choose between the two by asking one question: does this produce a value for the template (computed), or does it do something to the outside world (effect)?
Common mistakes with derived inputs
- Writing to an input.
this.name.set('x')does not compile, because an input signal has noset(). If the child must change a value that the parent supplies, usemodel(), which a later chapter covers, or emit an output and let the parent decide. - Copying an input into a writable signal in the constructor. This captures only the initial value. If the child needs a local, editable value that resets when the input changes, that is a different tool (
linkedSignal()). Do not simulate it with an effect that callsset(). - Using
effect()to compute a value. Setting a signal inside an effect to mirror another signal adds a delay and extra change detection work. Acomputed()expresses the same relationship directly. - Forgetting to call the signal.
{{ initials }}prints the function, andthis.name.split(' ')fails becausenameis a signal, not a string. Callname(). - Assuming string inputs are numbers. A static attribute such as
size="20"is a string unless the input has a transform. Computing with it withoutnumberAttributeproduces string concatenation or a type error.
Exercise
A component declares price = input.required<number>(); and label = 'Price: ' + this.price();. The template shows {{ label }}. What goes wrong, and how do you fix it?
Show answer
The field initializer runs during construction, before Angular binds the input. Reading a required input at that point throws NG0950. Even for an optional input, the label would be built once from the default and never update. Fix it with label = computed(() => 'Price: ' + this.price()); and read it in the template as {{ label() }}.
Exercise
Write a computed() named isEmpty for an input items = input<string[]>([]) that is true when the list has no entries. When does the function rerun, and what happens if the parent passes a new empty array?
Show answer
isEmpty = computed(() => this.items().length === 0);. The function reruns the next time it is read after the items input receives a new value. If the parent passes a new empty array, the function reruns, but the result is true again. Because the new result equals the cached one, readers of isEmpty are not notified.