Sub topic 1
What lifecycle hooks are and when Angular calls them
Prerequisites
This chapter assumes you already know:
- Basic TypeScript, including classes and interfaces.
- How to create a basic Angular component with a template.
- Property and event binding in templates.
- The basics of RxJS observables and subscriptions.
You do not need to know change detection internals yet. Later chapters cover that.
What a lifecycle hook is
Angular creates every component, updates it while the application runs, and destroys it when it is no longer needed. A lifecycle hook is a method with a specific name that Angular calls at one of these moments. You write the method, and Angular decides when to run it. You never call it yourself.
Each hook has a matching TypeScript interface, such as OnInit for ngOnInit. Implementing the interface is optional, because Angular looks for the method by name. The interface still helps. The compiler reports a misspelled method name, such as ngOnInt, instead of letting it silently never run.
Hooks work on components and directives. The hooks about content and views mostly matter for components, because a component owns a template.
The hooks and their moments
The table lists the hooks in the order Angular calls them for a single component. The constructor is not a hook, but it is the first step.
| Step | Method | Runs | Typical use |
|---|---|---|---|
| 1 | `constructor` | Once | Dependency injection and simple field setup |
| 2 | `ngOnChanges` | Before `ngOnInit`, then on every change to a bound input | React to new input values |
| 3 | `ngOnInit` | Once | Initialization that needs inputs |
| 4 | `ngDoCheck` | Every change detection run | Custom change checks |
| 5 | `ngAfterContentInit` | Once | First access to projected content |
| 6 | `ngAfterContentChecked` | Every change detection run | Respond after projected content is checked |
| 7 | `ngAfterViewInit` | Once | First access to the component's own view |
| 8 | `ngAfterViewChecked` | Every change detection run | Respond after the view is checked |
| 9 | `ngOnDestroy` | Once, just before removal | Cleanup |
Two rules explain most of the table:
- Hooks named
...Initrun once. Hooks named...Checkor...Checkedrun on every change detection pass, so they run very often. - Hooks about inputs run before hooks about content. Hooks about content run before hooks about the view. This is the order in which Angular makes each part ready.
Following the flow
The diagram shows the path of one component from creation to removal.
Read the diagram in two phases. The first pass runs everything from the constructor to ngAfterViewChecked. Each later pass skips the Init hooks. It runs ngOnChanges only if a bound input changed, and then runs ngDoCheck and the two Checked hooks. When the component leaves the page, Angular runs ngOnDestroy once.
A worked example
This component logs each of its early hooks and its destruction. It is the same pattern you will use to check the order in your own code.
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');
}
}A parent component can drive the card. The buttons below change the input and remove the card.
import { Component } from '@angular/core';
import { UserCardComponent } from './user-card.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [UserCardComponent],
template: `
<button (click)="id = 'u2'">Change user</button>
<button (click)="show = !show">Toggle card</button>
@if (show) {
<app-user-card [userId]="id" />
}
`,
})
export class AppComponent {
id = 'u1';
show = true;
}When the page loads, the console shows:
constructor: inputs are not set yetfollowed by an empty string. Angular has created the object but has not bound anything to it.ngOnChanges undefined -> u1 first: true. The previous value isundefinedbecause there was no earlier value.ngOnInit: inputs are set u1.
After you click Change user, the console adds ngOnChanges u1 -> u2 first: false. ngOnInit does not run again. After you click Toggle card, the @if block removes the component and Angular calls ngOnDestroy.
What each stage guarantees
The hooks exist because the component is only partly ready at each step. Knowing what is ready tells you which hook to use.
- In the constructor, the object exists and injected services are available. Inputs, queries and the template are not ready.
- In
ngOnChangesandngOnInit, bound input values are set. The component's own view is still being created, so view queries are not safe to read. - In
ngAfterContentInit, content that a parent projected into your component through<ng-content>has been initialized and content queries are resolved. - In
ngAfterViewInit, your component's template and its child components have been created, and view queries are resolved. - In
ngOnDestroy, the component is about to be removed. This is the last place to release anything you started.
A short example shows the view stage. The @ViewChild reference points to the input only after the view exists, so the focus call goes in ngAfterViewInit.
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-focus-input',
standalone: true,
template: `<input #box type="text" />`,
})
export class FocusInputComponent implements AfterViewInit {
@ViewChild('box') box!: ElementRef<HTMLInputElement>;
ngAfterViewInit(): void {
this.box.nativeElement.focus();
}
}Details that surprise people
ngOnChanges is not always called. Angular calls it only when a bound input changes through a template binding. If a component has no inputs, or you set a property from code (instance.userId = 'x'), the hook does not run. Changing an object's property in place does not count either. Angular compares input values by reference, so a mutated object looks unchanged.
The Checked hooks run constantly. ngDoCheck, ngAfterContentChecked and ngAfterViewChecked run on every change detection pass, which can happen after any click, timer or HTTP response in the app. Heavy work in them slows the whole interface.
Render hooks work differently. afterNextRender and afterRender are not methods on an interface. You register a callback, usually in the constructor. Angular runs it after it has rendered, and only in the browser. This suits DOM work that must not run during server-side rendering.
import { Component, afterNextRender } from '@angular/core';
@Component({
selector: 'app-measure',
standalone: true,
template: `<div>Content to measure</div>`,
})
export class MeasureComponent {
constructor() {
afterNextRender(() => {
console.log('Rendered in the browser; safe to touch the DOM');
});
}
}Cleanup has two forms. The classic form is ngOnDestroy. A newer form registers cleanup with DestroyRef, for example through takeUntilDestroyed. Both are covered in later chapters.
Choosing a hook
Start from the question you are asking:
| You want to... | Use |
|---|---|
| Inject services or set simple defaults | `constructor` |
| Compare old and new input values | `ngOnChanges` |
| Load data or start work that depends on inputs | `ngOnInit` |
| Read projected content | `ngAfterContentInit` |
| Read your own template elements or child components | `ngAfterViewInit` |
| Run browser-only DOM work | `afterNextRender` or `afterRender` |
| Stop timers, subscriptions and listeners | `ngOnDestroy` or `DestroyRef` |
The later chapters take each row in turn.
Exercise
A component has an @Input() userId. Its parent sets [userId]="id" in the template. On first render, which of these runs first: the constructor, ngOnInit, or ngOnChanges? What value does this.userId have in the constructor, and what is firstChange in the first ngOnChanges call?
Show answer
The constructor runs first, then ngOnChanges, then ngOnInit. In the constructor, this.userId still has its field initializer value (an empty string in the example), because Angular binds inputs after it creates the object. In the first ngOnChanges call, firstChange is true and previousValue is undefined.
Exercise
Why does a component that logs inside ngAfterViewChecked print many lines after a single button click, while a component that logs inside ngAfterViewInit prints one line in total?
Show answer
ngAfterViewInit is an Init hook, which runs once after the first view is created. ngAfterViewChecked runs after every change detection pass, and a click starts a pass. Timers, HTTP responses and other events start further passes, each of which calls the hook again.