Sub topic 16
Component Lifecycle Hooks
This chapter assumes you know signal-based inputs from the inputs and outputs chapter, and viewChild queries from the previous chapter. Every component goes through a lifecycle. Angular creates it, sets its inputs, renders its template, checks it for changes, and finally destroys it. Lifecycle hooks are methods Angular calls at each of these points, so your code can run at the right moment.
The hooks in order
Each hook is a method with a fixed name. You can also implement the matching interface, such as OnInit, so the compiler checks the method signature.
| Hook | When it runs | Typical use |
|---|---|---|
| `constructor` | When the class is created, before inputs are set | Inject dependencies only |
| `ngOnChanges` | Before `ngOnInit`, then each time an input changes | React to specific input changes |
| `ngOnInit` | Once, after the first inputs are set | Setup that needs input values |
| `ngDoCheck` | Every change detection pass | Custom change checks (rarely needed) |
| `ngAfterContentInit` | Once, after projected content is ready | Read `contentChild` results |
| `ngAfterViewInit` | Once, after the component's view is rendered | Read `viewChild` results, touch the DOM |
| `ngOnDestroy` | Just before the component is removed | Clean up timers and subscriptions |
Angular also has ngAfterContentChecked and ngAfterViewChecked. They run after every check, so they are expensive places to put work.
A worked example
The ClockComponent below uses an input in ngOnInit, touches the DOM in ngAfterViewInit, and stops its timer in ngOnDestroy.
import {
AfterViewInit, Component, ElementRef, OnDestroy, OnInit,
input, signal, viewChild
} from '@angular/core';
@Component({
selector: 'app-clock',
template: `<p #display>{{ label() }}: {{ time() }}</p>`
})
export class ClockComponent implements OnInit, AfterViewInit, OnDestroy {
label = input('Time');
time = signal(new Date().toLocaleTimeString());
display = viewChild.required<ElementRef<HTMLParagraphElement>>('display');
private timerId?: ReturnType<typeof setInterval>;
ngOnInit() {
// Inputs are available here, but not in the constructor.
console.log(`Starting clock "${this.label()}"`);
this.timerId = setInterval(() => {
this.time.set(new Date().toLocaleTimeString());
}, 1000);
}
ngAfterViewInit() {
// The view is rendered, so the query result exists.
this.display().nativeElement.style.color = 'teal';
}
ngOnDestroy() {
clearInterval(this.timerId);
}
}If a parent shows <app-clock /> inside an @if block, the timer stops when the condition becomes false. Without ngOnDestroy, the interval would keep running after the component is gone. That is a memory leak.
Common errors
- Reading inputs in the constructor. Inputs are not set yet. With
input.required(), reading one in the constructor throws an error. Move that code tongOnInit. - Changing bound state in
ngAfterViewInit. If you update a value the template has already displayed, development mode reportsExpressionChangedAfterItHasBeenCheckedError. Set the value earlier, or use a signal so Angular schedules another render. - Forgetting cleanup. Timers, event listeners added by hand, and subscriptions all need to be stopped in
ngOnDestroy.
Exercise
A component reads this.userId() from a required signal input in its constructor to start loading data, and the app throws an error. Why, and which hook should the code move to?
Show answer
Angular sets inputs after the constructor runs, so the required input has no value yet and reading it throws. Move the code to ngOnInit, which runs once after the first input values are set. To react to later changes too, use ngOnChanges or a signal-based computed/effect.
Exercise
Why does ClockComponent clear its interval in ngOnDestroy, and what happens if it doesn't?
Show answer
setInterval keeps running regardless of the component's lifecycle. Without clearing it, the callback keeps firing after the component is removed. It holds a reference to the destroyed component, so memory leaks and work is wasted.