Sub topic 16
Component Lifecycle Hooks
Angular creates a component, renders it, checks it again and again for changes, and eventually destroys it. Lifecycle hooks are methods Angular calls at fixed points in that sequence. They let you run setup, react to input changes, touch the rendered DOM, and clean up.
This chapter assumes you know signal-based input(), viewChild(), and content projection from earlier chapters, and that you are comfortable with TypeScript classes and interfaces.
The Hooks and Their Order
Each hook is an optional method on the component class. Angular calls a hook only if you define it. Each one has a matching interface (OnInit, OnDestroy, and so on). Implementing the interface is optional, but it makes the compiler catch typos such as ngOnInt.
| Hook | When it runs | Typical use |
|---|---|---|
| `constructor` | When the class is instantiated, before any inputs are set | `inject()` calls, registering render or destroy callbacks |
| `ngOnChanges` | Before `ngOnInit`, then every time a bound input changes | React to specific input changes, using previous values |
| `ngOnInit` | Once, after the first `ngOnChanges` | One-time setup that needs input values |
| `ngDoCheck` | On every change detection pass | Custom change checks (rarely needed) |
| `ngAfterContentInit` | Once, after projected content is initialized | Read `contentChild` results |
| `ngAfterContentChecked` | After every check of projected content | Rarely needed |
| `ngAfterViewInit` | Once, after the component's own view and child views are initialized | Read `viewChild` results |
| `ngAfterViewChecked` | After every check of the view | Rarely needed |
| `ngOnDestroy` | Once, just before Angular removes the component | Release timers, subscriptions, observers |
Content hooks run before view hooks. The reason is that projected content belongs to the parent's template, so the parent initializes it before Angular finishes building this component's own view.
Setup, Input Changes, and Cleanup
The example below uses the three hooks you will write most often. ngOnChanges receives a SimpleChanges object keyed by input name. Each entry holds previousValue, currentValue, and firstChange. This works for signal inputs as well as @Input properties.
import { Component, OnChanges, OnDestroy, OnInit, SimpleChanges, input, signal } from '@angular/core';
@Component({
selector: 'app-clock',
template: `<p>{{ label() }}: {{ now().toLocaleTimeString() }}</p>`
})
export class ClockComponent implements OnChanges, OnInit, OnDestroy {
label = input.required<string>();
intervalMs = input(1000);
now = signal(new Date());
private timerId?: ReturnType<typeof setInterval>;
ngOnChanges(changes: SimpleChanges) {
const change = changes['intervalMs'];
if (change && !change.firstChange) {
console.log(`Interval changed from ${change.previousValue} to ${change.currentValue}`);
this.startTimer();
}
}
ngOnInit() {
this.startTimer();
}
ngOnDestroy() {
clearInterval(this.timerId);
}
private startTimer() {
clearInterval(this.timerId);
this.timerId = setInterval(() => this.now.set(new Date()), this.intervalMs());
}
}The timer writes to a signal, not a plain field. That way the template updates whether the app uses Zone.js or runs zoneless, which is the default for new projects in current Angular versions.
When ngOnChanges is the wrong tool
With signal inputs you can often skip ngOnChanges. A value derived from an input belongs in computed(). A side effect that should rerun when an input changes belongs in effect(). ngOnChanges is still useful when you need the previous value or want to handle several inputs that changed in the same pass.
Cleanup with DestroyRef and Render Callbacks
You can also register cleanup without a hook method. inject(DestroyRef) returns an object whose onDestroy() callback runs at the same time as ngOnDestroy. Code that sets something up can then clean it up in the same place, and you can do this from helper functions as well as from the class.
afterNextRender() runs a callback once, after Angular next writes to the DOM. afterEveryRender() runs after every render. Both must be called in an injection context, such as the constructor. They do not run during server-side rendering, so they are the safe place for browser-only APIs like ResizeObserver or for measuring layout.
import { Component, DestroyRef, ElementRef, afterNextRender, inject, signal, viewChild } from '@angular/core';
@Component({
selector: 'app-resize-box',
template: `<div #box class="box">Width: {{ width() }}px</div>`,
styles: `.box { resize: horizontal; overflow: auto; border: 1px solid #999; padding: 0.5rem; }`
})
export class ResizeBoxComponent {
box = viewChild.required<ElementRef<HTMLDivElement>>('box');
width = signal(0);
constructor() {
const destroyRef = inject(DestroyRef);
afterNextRender(() => {
const observer = new ResizeObserver(entries => {
this.width.set(Math.round(entries[0].contentRect.width));
});
observer.observe(this.box().nativeElement);
destroyRef.onDestroy(() => observer.disconnect());
});
}
}Common Errors
ExpressionChangedAfterItHasBeenCheckedError
In development mode, Angular runs a second check after each pass to confirm that template values have not changed. Suppose you set a plain field in ngAfterViewInit or ngAfterViewChecked, and the template has already read that field. The second check sees a different value and throws error NG0100. To fix it, compute the value earlier (in ngOnInit or with computed()), or store it in a signal. Signal writes schedule a new render instead of quietly changing a value Angular has already checked.
Reading queries too early
viewChild results do not exist until the view is created. Calling this.box() on a viewChild.required in the constructor or in ngOnInit throws, because the element is not resolved yet. Read view queries in ngAfterViewInit, in afterNextRender, or in a computed() or effect() that runs once the query resolves. Read content queries in ngAfterContentInit or later.
Heavy work in checked hooks
ngDoCheck, ngAfterContentChecked, and ngAfterViewChecked run on every change detection pass, which can mean many times per second. Logging, DOM reads, or deep comparisons in these hooks slow the whole app. If you think you need one of them, a signal or computed() usually does the job with less code.
Forgetting cleanup
Intervals, addEventListener calls on window or document, observers, and manual RxJS subscriptions all survive after the component is removed. They leak memory and keep calling code on a dead component. Pair each one with ngOnDestroy or DestroyRef.onDestroy. For observables, takeUntilDestroyed() from @angular/core/rxjs-interop handles this for you.
ngOnChanges does not fire for internal mutation
ngOnChanges runs only when a template binding passes a new value, or when you call ComponentRef.setInput(). It compares by reference. If the parent mutates an array it already passed in (for example with push), the reference stays the same and the hook does not fire. Pass a new array or object instead.
Exercises
Exercise
A child component has items = input.required<string[]>() and logs this.items().length in its constructor. The app throws NG0950. Why, and where should the log go?
Show answer
Angular sets inputs after it constructs the class, so a required input has no value yet in the constructor. Move the log to ngOnInit, or into an effect() that reads this.items().
Exercise
A component sets this.title = 'Ready' inside ngAfterViewInit, and its template shows {{ title }}. In development you see ExpressionChangedAfterItHasBeenCheckedError. Give two fixes.
Show answer
Set the value earlier, for example in ngOnInit or as a field initializer, so it is final before the view is checked. Or make title a signal and call this.title.set('Ready'), which schedules a new render instead of changing an already-checked value.
Exercise
You add a window.addEventListener('resize', handler) call in a component's constructor. Write the line that removes the listener when the component is destroyed, without defining ngOnDestroy.
Show answer
inject(DestroyRef).onDestroy(() => window.removeEventListener('resize', handler)); called in the constructor, where inject() is allowed.
Exercise
A parent does this.list.push('new') on an array bound to a child's input, and the child's ngOnChanges does not run. Explain and fix it.
Show answer
ngOnChanges compares input values by reference. push changes the same array, so the reference does not change and Angular sees no change. Assign a new array, for example this.list = [...this.list, 'new'], or update a signal with list.update(l => [...l, 'new']).