Sub topic 14
Signals and lifecycle hooks together
This chapter assumes you know the hooks from the earlier chapters: ngOnChanges, ngOnInit, the view hooks, ngOnDestroy and DestroyRef. It also assumes you have seen signals (signal, computed) at a basic level. Here you will see how signal-based APIs replace some hooks, coexist with others, and where timing differences can surprise you.
Which hooks signals replace
Signals do not remove the lifecycle. Angular still creates, checks and destroys components in the same order. Signals change how you express reacting to a value. Much of what ngOnChanges and ngAfterViewInit were used for can now be written as a reactive declaration.
| Old pattern | Signal-based equivalent |
|---|---|
| `@Input()` plus `ngOnChanges` to derive a value | `input()` plus `computed()` |
| `ngOnChanges` to run a side effect when an input changes | `effect()` reading the input signal |
| `@ViewChild` read in `ngAfterViewInit` | `viewChild()` read inside `effect()` or `afterNextRender` |
| `@ContentChild` read in `ngAfterContentInit` | `contentChild()` |
| Manual `subscribe` plus `ngOnDestroy` | `toSignal()` or `takeUntilDestroyed()` |
| `ngOnDestroy` for cleanup of a side effect | `onCleanup` callback inside `effect()` |
ngOnInit, ngDoCheck and ngOnDestroy remain useful. Signals do not give you a "run once after setup" moment or a custom change check.
Signal inputs and when they can be read
A signal input is declared with input() or input.required(). It is a read-only signal, so you read it by calling it: this.price().
Timing matches the classic @Input. Inputs are set after the constructor and before ngOnInit. The difference is what happens when you read too early:
- A required input read in the constructor or a field initializer throws an error (NG0950), because no value exists yet.
- An optional input read at that point returns its default value, not the value the parent binds.
A signal input is usually read inside a computed() or effect(), so it is evaluated later, after Angular has set it. Direct reads belong in ngOnInit or later.
Signal inputs are still reported to ngOnChanges, so you can mix the two in one component. A new component, though, rarely needs ngOnChanges at all, because computed and effect track exactly what they read.
Deriving state with computed
A computed() is lazy and memoized. It runs only when something reads it, and it recalculates only when a signal it read last time has changed. This is the replacement for the "copy the input into a field in ngOnChanges" pattern.
import { Component, ElementRef, computed, effect, input, viewChild } from '@angular/core';
@Component({
selector: 'app-price-tag',
standalone: true,
template: `
<p>{{ label() }}</p>
<input #qty type="number" />
`,
})
export class PriceTagComponent {
readonly price = input.required<number>();
readonly currency = input('USD');
readonly qtyBox = viewChild<ElementRef<HTMLInputElement>>('qty');
readonly label = computed(() => `${this.price().toFixed(2)} ${this.currency()}`);
constructor() {
effect((onCleanup) => {
const label = this.label();
const id = setTimeout(() => console.log('price settled:', label), 500);
onCleanup(() => clearTimeout(id));
});
effect(() => {
const box = this.qtyBox();
if (box) {
box.nativeElement.focus();
}
});
}
}Reading label() in the template needs no hook. When the parent changes price, label is marked stale and the template updates in the next change detection pass. The old equivalent would have been an ngOnChanges that assigned this.label = ..., with the risk of forgetting a branch.
Side effects with effect
An effect() runs a function and re-runs it whenever a signal it read changes. Three rules matter for lifecycle work.
- It needs an injection context. Create effects in the constructor or in a field initializer. Calling
effect()insidengOnInitthrows, because the injection context has ended. If you must create one later, pass aninjectoroption. - It is cleaned up automatically. An effect created in a component is destroyed with the component, so you do not call
ngOnDestroyfor it. Use theonCleanupcallback to undo work from the previous run, as the timer above does. That callback also runs when the effect is destroyed. - It runs during change detection, not at a fixed hook. Effects run at least once, and the first run happens after the component's inputs are available. Never rely on the exact point where an effect runs relative to
ngAfterViewInit.
The second effect above reads qtyBox(). Before the view exists, that signal holds undefined. After Angular builds the view, the signal gets the element, the effect re-runs, and the input is focused. You get the same result as the ngAfterViewInit example, with no hook and no ! assertion. The if (box) guard handles the first run.
Effects versus render hooks
An effect is not a DOM hook. It may run before Angular has updated the view for the same change, so reading layout there can give stale measurements. For DOM work, such as measuring, focusing a third-party widget, or touching window, use afterNextRender or afterRender, as covered in the render hooks chapter. A common combination is to read a signal in an effect and write DOM-facing code in a render hook, or to read signals directly inside the render callback.
Cleanup with signals and RxJS
Interop functions follow the same rule as effects: they need an injection context, and they clean up through DestroyRef.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-uptime',
standalone: true,
template: `<p>Uptime: {{ seconds() }}s</p>`,
})
export class UptimeComponent {
readonly seconds = toSignal(interval(1000), { initialValue: 0 });
}toSignal subscribes immediately and unsubscribes when the component is destroyed. Neither ngOnInit nor ngOnDestroy is needed. If you called toSignal inside ngOnInit, Angular would throw an injection context error (NG0203). Create it as a field or in the constructor.
For one-off teardown that does not fit these helpers, inject DestroyRef and call onDestroy. That is the same mechanism the helpers use.
Pitfalls specific to signals
- Reading a required input in the constructor. Move the read into
computed,effectorngOnInit. - Reading a signal in
ngOnInitand expecting updates. A plain read there is a one-time snapshot. Later changes do not re-runngOnInit. If you need updates, usecomputedoreffect. - Reading a query signal too early.
viewChild()isundefineduntil the view is created. Guard againstundefinedand read it in an effect or render hook. - Writing signals inside
computed. Computed functions must be pure. Writing to a signal there is an error. - Tracking more than you intend. An effect re-runs when any signal it reads changes. To read a signal without tracking it, wrap the read in
untracked(() => ...). - Assuming effect timing. Effects batch and run during change detection. Code that needs "after the DOM updated" should use a render hook.
Exercise
A component declares readonly id = input.required<string>(); and has the field private readonly upper = this.id().toUpperCase();. What goes wrong, and how do you fix it?
Show answer
The field initializer runs during construction, before Angular sets inputs, so reading the required input throws NG0950. Declare readonly upper = computed(() => this.id().toUpperCase());. The computed is lazy, so it first reads id() after the input is set, and it recalculates when the input changes.
Exercise
You need to start a polling timer whenever the userId signal input changes and stop the previous timer. Which API do you use, where do you create it, and how is the old timer stopped?
Show answer
Use effect() created in the constructor. Read this.userId() inside it, start the timer, and register onCleanup(() => clearInterval(id)). Angular runs the cleanup before each re-run and when the component is destroyed, so no ngOnDestroy is needed.