Sub topic 11
When input values are available
This chapter covers the moment a signal input holds the value the parent bound to it. It assumes you can declare inputs with input() and input.required(), read a signal by calling it, and use computed(). Reading an input too early is a common source of errors, so the chapter also covers how to avoid that.
Inputs are not set in the constructor
Angular creates a component in two steps. It first calls the constructor, then it sets the inputs the parent bound. Class field initializers run as part of the constructor, so at that point no binding has been applied yet.
The consequences differ for optional and required inputs.
- An optional input returns its initial value, the one you passed to
input(). The parent's value is not available yet. - A required input has no initial value. Reading it throws a runtime error,
NG0950: Input is required but no value is available yet.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>Hello, {{ name() }} ({{ role() }})</p>`,
})
export class Greeting {
name = input.required<string>();
role = input('guest');
constructor() {
console.log(this.role()); // always 'guest' here, even if the parent passed 'admin'
console.log(this.name()); // throws NG0950
}
}The same rule applies to field initializers. This line fails for the same reason as the constructor read:
shout = this.name().toUpperCase(); // runs during construction, throws NG0950The order of events
For one component instance, Angular follows this sequence:
- The parent's template is checked and its binding expressions are evaluated.
- Angular creates the child and runs its constructor.
- Angular writes the bound values into the child's input signals.
- Angular runs
ngOnChanges(if defined), thenngOnInit, once. - Angular renders the child's template.
- Later, when a binding in the parent changes, Angular writes the new value into the signal and the dependent computed values, effects and template bindings update.
Static attribute values such as role="admin" also arrive in step 3, after the constructor. A static value does not make the input available earlier.
Where it is safe to read an input
| Where you read it | Optional input | Required input |
|---|---|---|
| Constructor or field initializer, read directly | Initial value only | Throws NG0950 |
| Inside `computed()` or `effect()` | Current bound value | Current bound value |
| `ngOnInit` and later | Bound value | Bound value |
| Template | Bound value | Bound value |
| Event handler after creation | Bound value | Bound value |
The template is safe because Angular renders it only after the inputs are set. Event handlers are safe because users can only trigger them after the component exists.
Reading inputs reactively
Because an input is a signal, you can wrap a read in a reactive function instead of worrying about timing. A computed() is lazy. It does not run when you define it. It runs the first time something reads it, and by then the inputs are set.
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-shout',
template: `<p>{{ loud() }}</p>`,
})
export class Shout {
text = input.required<string>();
// Safe: the callback is not called until the template reads loud()
loud = computed(() => this.text().toUpperCase());
}The computed value recalculates whenever text changes. This is the preferred way to derive state, because it covers both the first value and every later one. Lifecycle hooks only cover the first.
Reacting to changes with effect()
For side effects, create an effect() in the constructor. Angular runs an effect after the component's inputs have been set, so a required input is safe to read inside it. The effect runs once at first and again whenever a signal it read changes.
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();
});
}
}Reserve effects for work outside the component's own state, such as the document title, logging, or calling a non-Angular library. If you only need a value derived from an input, use computed().
Using lifecycle hooks
ngOnInit runs once, after the first input values are set. It is a good place for one-time setup that needs the initial value.
import { Component, OnInit, input } from '@angular/core';
@Component({
selector: 'app-product-detail',
template: `<p>Product {{ productId() }}</p>`,
})
export class ProductDetail implements OnInit {
productId = input.required<number>();
ngOnInit() {
console.log('First value:', this.productId());
}
}ngOnInit does not run again when the input changes. A component that loads data in ngOnInit from productId() will show stale data when the parent passes a different id to the same instance. This happens often, for example when a router reuses a component for /products/1 and /products/2. To handle it, read the input in a reactive context such as computed() or effect(), so the work is redone on every change.
ngOnChanges still works with signal inputs and runs before ngOnInit and on each later change. New code rarely needs it, because computed() and effect() cover the same cases with less code.
Inputs are read-only
A signal input has no set() or update() method. The child cannot overwrite what the parent passed. This is by design. Data flows down through inputs and events flow up through outputs.
this.name.set('Ada'); // compile error: 'set' does not exist on InputSignalIf the child needs a local, modifiable copy, create a separate piece of state. For a value that both sides must change, use model(), which was covered earlier.
Changes within one change detection pass
Angular updates input signals during change detection of the parent, before it checks the child's template. Several inputs can change in the same pass, and the child sees them all together. A computed() that reads two inputs recalculates once for that pass, not once per input.
Angular does not evaluate a binding again unless something it depends on changed. If the parent passes the same object reference after mutating it in place, the input signal sees the same reference and nothing downstream updates. To trigger an update, pass a new object or array.
// Parent class: the child's input will not notice this
this.items.push(newItem);
// Parent class: a new array reference triggers the update
this.items = [...this.items, newItem];A worked example with defaults
The component below combines an optional input, a required input, a computed value and an effect. Each read sits in a place where the value is available.
import { Component, computed, effect, input } from '@angular/core';
@Component({
selector: 'app-price-tag',
template: `<span>{{ label() }}</span>`,
})
export class PriceTag {
amount = input.required<number>();
currency = input('USD');
label = computed(() =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: this.currency(),
}).format(this.amount())
);
constructor() {
effect(() => {
console.log('Price is now', this.label());
});
}
}If you used console.log(this.label()) directly in the constructor, the computed() would run immediately, read amount() too early, and throw. Putting the read inside effect() delays it until the inputs exist.
Summary of rules
- Do not read required inputs in the constructor or in field initializers.
- Optional inputs read before binding return their initial value, not an error.
- Use
computed()for values derived from inputs andeffect()for side effects. Both react to the first value and to every change. ngOnInitruns once. Do not rely on it to react to later changes.- Pass new object references to make a changed input visible.
Exercise
A component declares id = input.required<number>(); and label = 'Item ' + this.id(); as a field. It throws NG0950 when created. Explain why, and show a fix that keeps label up to date when the parent changes id.
Show answer
Field initializers run during construction, before Angular sets the inputs, so this.id() has no value yet and the required input throws. Replace the field with a computed value: label = computed(() => 'Item ' + this.id());. The callback runs only when label() is first read, after the inputs are set, and it recalculates whenever id changes. In the template, use {{ label() }}.
Exercise
A component loads user data in ngOnInit using userId(). A router reuses the same component instance when the URL changes from /users/1 to /users/2, and the page still shows user 1. What causes this, and how do you fix it?
Show answer
ngOnInit runs only once, after the first input values are set, so it does not run when userId changes. Move the loading logic into an effect() created in the constructor that reads userId(), so it reruns each time the input changes. A computed() also works if the data is derived synchronously.