Sub topic 1
What lifecycle hooks are and when Angular calls them
Prerequisites
This chapter assumes you can write TypeScript classes and interfaces, and that you can build a basic Angular component with a template. You should know property and event binding. You should also know what an RxJS observable and a subscription are, because cleanup comes up later in this tutorial.
What a lifecycle hook is
Angular creates, updates and destroys every component and directive in a predictable sequence. A lifecycle hook is a method with a fixed name that you add to your class. Angular calls it at one specific step of that sequence.
You do not call hooks yourself. You implement the method, and Angular finds it and runs it at the right time. Each hook has a matching interface, such as OnInit for ngOnInit. Implementing the interface is optional, but the compiler then warns you if you misspell the method name.
The stages of a component's life
A component moves through three broad stages.
- Creation. Angular calls the constructor, then sets the inputs.
- Updates. Each time change detection runs, Angular checks bindings, updates inputs, and refreshes the template.
- Destruction. Angular removes the component and calls its cleanup hook.
Change detection is the process that compares bound values with their previous values and updates the DOM. Most hooks are tied to it, which later chapters cover in detail.
The hooks at a glance
| Hook | When Angular calls it |
|---|---|
| `ngOnChanges` | Before `ngOnInit`, and again whenever a bound input changes |
| `ngOnInit` | Once, after the first `ngOnChanges` |
| `ngDoCheck` | On every change detection run |
| `ngAfterContentInit` | Once, after projected content is initialized |
| `ngAfterContentChecked` | After each check of projected content |
| `ngAfterViewInit` | Once, after the component's view is initialized |
| `ngAfterViewChecked` | After each check of the component's view |
| `ngOnDestroy` | Once, just before Angular removes the component |
Some hooks run once, and others run repeatedly. ngOnInit, ngAfterContentInit and ngAfterViewInit run one time. ngOnChanges, ngDoCheck and the Checked hooks can run many times, so keep their code cheap.
Seeing the order in code
The following component logs three hooks and the constructor. It shows that inputs are empty in the constructor and set by the time ngOnChanges and ngOnInit run.
import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-user-card',
standalone: true,
template: `<p>User: {{ userId }}</p>`,
})
export class UserCardComponent implements OnChanges, OnInit, OnDestroy {
@Input() userId = '';
constructor() {
console.log('constructor: inputs are not set yet', this.userId);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['userId']) {
const change = changes['userId'];
console.log('ngOnChanges', change.previousValue, '->', change.currentValue, 'first:', change.firstChange);
}
}
ngOnInit(): void {
console.log('ngOnInit: inputs are set', this.userId);
}
ngOnDestroy(): void {
console.log('ngOnDestroy: release resources here');
}
}If a parent renders <app-user-card userId="42" />, the console shows the constructor line first, with an empty userId. Then ngOnChanges logs the change from '' to '42' with first: true. Then ngOnInit logs 42. When the parent removes the component, ngOnDestroy logs last.
Common mistakes at this stage
- Reading an input in the constructor. It still holds its default value there, so use
ngOnInitorngOnChanges. - Expecting
ngOnChangesto fire when a component has no bound inputs. Angular only calls it when a bound input changes. - Putting heavy work in
ngDoCheckor aCheckedhook. These run on every change detection pass and slow the whole app.
The next chapter explains why initialization work belongs in ngOnInit rather than the constructor.
Exercise
A component logs a message in its constructor, ngOnInit, and ngOnChanges. In what order do the messages appear when the component is created with a bound input, and which of the three sees the input value set?
Show answer
The order is constructor, then ngOnChanges, then ngOnInit. The constructor sees only the default value. ngOnChanges and ngOnInit both see the bound input value.