In the RxJS Basics lesson, a timer that was never stopped kept running after its component was removed. In the Route Parameters lesson, ngOnInit appeared without much explanation. Both belong to the same topic: lifecycle hooks.
A lifecycle hook is a method Angular itself calls at certain moments in a component's life (its lifecycle). The moments are: when the inputs from its parent arrive or change, after the component is ready, after its view is in the DOM, and right before the component is removed. Picture one cook's shift in Jali's kitchen:
- The cook arrives and signs the attendance sheet: the constructor.
- They receive the order slip: the inputs arrive, and
ngOnChangesis called. - They start cooking:
ngOnInit. - The pancake is on the plate and can be handled:
ngAfterViewInit, when the template is in the DOM. - The order changes halfway:
ngOnChangesis called again. - They go home and turn off the stove:
ngOnDestroy.
If the cook forgets to turn off the stove, the fire keeps burning after they have left. In a component, the stove is a timer or a subscription that you started yourself.
The order of the hooks
This Order component writes to the console in every hook:
import { AfterViewInit, Component, ElementRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild } from '@angular/core'
@Component({
selector: 'app-order',
standalone: true,
template: `
<p>{{ title }}</p>
<input #note placeholder="Note" />
`,
})
export class Order implements OnChanges, OnInit, AfterViewInit, OnDestroy {
@Input() menu = ''
@ViewChild('note') note!: ElementRef<HTMLInputElement>
title = ''
private timer = 0
constructor() {
console.log('constructor: menu =', JSON.stringify(this.menu))
}
ngOnChanges(changes: SimpleChanges) {
const c = changes['menu']
console.log('ngOnChanges:', JSON.stringify(c.previousValue), '->', JSON.stringify(c.currentValue))
}
ngOnInit() {
console.log('ngOnInit: menu =', JSON.stringify(this.menu))
this.title = 'Order: ' + this.menu
this.timer = setInterval(() => console.log('checking status', this.menu), 2000)
}
ngAfterViewInit() {
console.log('ngAfterViewInit: note =', this.note.nativeElement.tagName)
}
ngOnDestroy() {
clearInterval(this.timer)
console.log('ngOnDestroy')
}
}
The App component shows Order with @if (open) { <app-order [menu]="menu" /> }, plus a Change menu button and a Close button. Close removes Order from the page through that @if. This is the console output, exactly as Angular 18 prints it:
constructor: menu = ""
ngOnChanges: undefined -> "Special Egg Pancake"
ngOnInit: menu = "Special Egg Pancake"
ngAfterViewInit: note = INPUT
(click Change menu)
ngOnChanges: "Special Egg Pancake" -> "Chocolate Cheese Pancake"
(click Close)
ngOnDestroy
| Hook | Called when | Usually used for |
|---|---|---|
constructor |
the class is created, before the inputs are set | inject() and initial property values |
ngOnChanges |
before ngOnInit, then every time an input from the parent gets a new value |
calculating again from inputs |
ngOnInit |
once, after the first ngOnChanges |
first work that needs inputs: fetching data, starting subscriptions |
ngAfterViewInit |
once, after this component's template is in the DOM | @ViewChild, focusing an element |
ngOnDestroy |
once, right before the component is removed | stopping timers and subscriptions |
implements OnInit on the class line is a promise to TypeScript that this class has an ngOnInit method. Angular calls the method by its name, so implements OnInit isn't required by Angular. It helps TypeScript instead: in a CLI project, a typo like ngOnInt() is refused right away, because the class no longer satisfies OnInit.
constructor or ngOnInit
Angular creates the class first, then fills the inputs from its parent. When the constructor runs, menu still holds its own initial value, ''. So what gets printed is constructor: menu = "", not the pancake's name. An input with no initial value (@Input() menu!: string) even holds undefined.
ngOnInit is called after the inputs are set for the first time, so this.menu there is already 'Special Egg Pancake'. The rule: the constructor for inject() and initial values, ngOnInit for work that needs inputs. The first exercise uses the same pattern: message = 'Loading...' is changed to 'Component initialised!' inside ngOnInit(), and <p>{{ message }}</p> shows it.
But ngOnInit only runs once. After you click Change menu, title stays Order: Special Egg Pancake, even though menu is now Chocolate Cheese Pancake. If something must change every time the input changes, put it in ngOnChanges, or read {{ menu }} directly in the template.
ngOnChanges and SimpleChanges
This version of ngOnChanges updates title every time menu changes:
ngOnChanges(changes: SimpleChanges) {
if (changes['menu']) {
this.title = 'Order: ' + changes['menu'].currentValue
}
}
changes(of typeSimpleChanges) holds one entry per input that changed. Each entry haspreviousValue(the old value),currentValue(the new value) andfirstChange(truefor the first call, beforengOnInit).ngOnChangesis only called for inputs bound by the parent. For a component used as<app-order />, with no[menu], Angular never callsngOnChanges. Changing a plain property inside the component itself doesn't trigger it either.- Angular compares the old value with the new one, and calls
ngOnChangesonly when they differ. If the parent sends the same text again,ngOnChangesisn't called. If the parent only changes what's inside an object (this.data.quantity = 2), it isn't called either, because it's still the same object. Send a new object:this.data = { ...this.data, quantity: 2 }.
ngOnDestroy: turn off what you turned on
setInterval is a JavaScript function that runs code again and again with a pause in between, here every 2 seconds. A setInterval started in ngOnInit keeps running until it's stopped. Without clearInterval (the function that stops it) in ngOnDestroy, this is what happens after Close:
| Time | With clearInterval |
Without clearInterval |
|---|---|---|
| Order open | checking status every 2 seconds |
checking status every 2 seconds |
| After Close | quiet | checking status still printed every 2 seconds |
| Open again | one timer | two timers, two lines every 2 seconds |
An interval that keeps running after Close is the same memory leak as the timer subscription in the RxJS Basics lesson. Whatever you start yourself (intervals, subscriptions, event listeners on window), you stop in ngOnDestroy. The second exercise uses two hooks: ngOnInit sets status = 'Active', so the <p> reads Status: Active, and ngOnDestroy prints Component destroyed.
ngAfterViewInit and @ViewChild
@ViewChild('note') is only filled in after the component's template is created. In the constructor and ngOnInit it holds undefined. In ngAfterViewInit it's already an ElementRef holding the <input>, so this.note.nativeElement.focus() is safe to write there.
Inside ngAfterViewInit, don't change a value the template is showing. Say App shows {{ title }} with title = 'start', then its ngAfterViewInit writes this.title = 'Order for ' + this.order.menu. But at that moment the view has already been checked. On an Eager component (checked at every template check, the default up to Angular 21), Angular in development mode (while the app is still being written) writes an error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'start'. Current value: 'Order for Special Egg Pancake'. Expression location: App component. In Angular 22, components use OnPush by default, and there's no error at all. The title stays start (tried in the exercise editor). Both results are signs that the value is written in the wrong place: calculate it in ngOnInit, or keep it in a signal.
Other options: functions that replace hooks. Newer Angular versions have functions you call in the constructor. With them, the cleanup code is written right next to the code that starts the work:
import { DestroyRef, ElementRef, ViewChild, afterNextRender, inject } from '@angular/core'
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'
import { interval } from 'rxjs'
// @Component(...) the same as above
export class Order {
@ViewChild('note') note!: ElementRef<HTMLInputElement>
constructor() {
const timer = setInterval(() => console.log('check status'), 2000)
inject(DestroyRef).onDestroy(() => clearInterval(timer))
interval(5000).pipe(takeUntilDestroyed()).subscribe(() => console.log('check delivery fee'))
afterNextRender(() => this.note.nativeElement.focus())
}
}
| Function | Replaces | When to pick it |
|---|---|---|
inject(DestroyRef).onDestroy(...) |
ngOnDestroy |
Stopping a timer or a listener, written next to the code that started it. |
takeUntilDestroyed() |
unsubscribe in ngOnDestroy |
An Observable subscription that must stop when the component is removed (the RxJS Basics lesson). |
afterNextRender(...) |
ngAfterViewInit for DOM work |
Focusing or measuring an element. It runs once after the next render, and only in the browser. |
Tried on Angular 22.2: the <input> gets focus right away. After the component is removed, check status and check delivery fee stop printing. The old hooks still work, and this lesson's exercises use them.
⚠️ Hooks used at the wrong moment
- Reading inputs in the constructor. They still hold their initial value (
'') orundefined. Move it tongOnInit. - Computing from an input only in
ngOnInit. When the parent changes the input,ngOnInitdoesn't run again. UsengOnChanges. - Changing what's inside an object and waiting for
ngOnChanges. The same object doesn't count as a change. Send a new object. - Not cleaning up in
ngOnDestroy. Timers and subscriptions keep running after the component is removed. - Exercise details. The grader looks for
this.<property> =inside the body ofngOnInit(), the wordOnInit(andOnDestroyin the second exercise), and a<p>whose content comes from{{ }}, not a sentence typed into the template.
TL;DR: A lifecycle hook is a method Angular itself calls at certain moments in a component's life. The order is: the constructor, ngOnChanges, ngOnInit, ngAfterViewInit, and at the end ngOnDestroy. In the constructor, the inputs aren't set by the parent yet (they still hold their own initial values), so work that needs inputs goes in ngOnInit, which only runs once. ngOnChanges(changes: SimpleChanges) runs every time the parent sends a new input value, with previousValue (the old value) and currentValue (the new value). An object whose contents were changed doesn't count as a change. @ViewChild is only filled in at ngAfterViewInit, after the template is in the DOM. Intervals and subscriptions you started yourself are stopped in ngOnDestroy, because otherwise they keep running after the component is removed. implements OnInit makes TypeScript check the method's name.
⚡ The class comes first, inputs come later
Write:
@Input() menu = ''
constructor() {
console.log('constructor: menu =', JSON.stringify(this.menu))
}
ngOnInit() {
console.log('ngOnInit: menu =', JSON.stringify(this.menu))
}
Guess first: the parent sends Special Egg Pancake to menu. What does the constructor print?
constructor: menu = "". Angular creates the class first, then fills the inputs from the parent. In ngOnInit, menu already holds "Special Egg Pancake".
Meaning: ngOnInit is a lifecycle hook: a method Angular itself calls once, after the inputs are set for the first time. So the constructor is for inject() and initial values, and ngOnInit is for work that needs inputs.
In the exercise, change a property inside the body of ngOnInit() (this.message = ...), and show it with <p>{{ message }}</p>.
⚡ ngOnChanges follows the input
Write:
ngOnChanges(changes: SimpleChanges) {
if (changes['menu']) {
this.title = 'Order: ' + changes['menu'].currentValue
}
}
Meaning: ngOnChanges runs every time the parent sends a new input value. changes holds one entry per input that changed, with previousValue (the old value) and currentValue (the new value). Here title is updated every time menu changes. An object whose contents changed doesn't count as a change, so send a new object.
⚡ ngOnDestroy: turn off what you turned on
Write:
ngOnDestroy() {
clearInterval(this.timer)
}
Meaning: Angular calls ngOnDestroy once, right before the component is removed. this.timer is the interval started with setInterval in ngOnInit, and it prints checking status every 2 seconds. Without clearInterval, checking status keeps printing after the component is removed. If the component is shown again, there are two timers. Intervals and subscriptions you started yourself are stopped here.