Sub topic 9
Cleaning up with ngOnDestroy
This chapter assumes you can write a standalone Angular component, bind inputs in templates, and subscribe to an RxJS observable. It covers ngOnDestroy, the hook Angular calls just before it removes a component.
Why cleanup matters
Angular destroys a component when it leaves the screen. Examples are a route change, a false @if condition, or a removed item in a @for loop. Angular removes the component's DOM and stops checking it. It does not stop anything you started yourself.
Timers, RxJS subscriptions, event listeners on window or document, and WebSocket connections keep running after the component is gone. The running callback holds a reference to the component, so the garbage collector cannot free it. This is a memory leak. The callback may also change state that no one sees, or call a server for no reason.
The ngOnDestroy hook
ngOnDestroy runs once, just before Angular destroys the component or directive. Implement the OnDestroy interface and release what you acquired. A common place to acquire resources is ngOnInit.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
template: `<p>Seconds: {{ seconds }}</p>`,
})
export class ClockComponent implements OnInit, OnDestroy {
seconds = 0;
private subscription?: Subscription;
ngOnInit(): void {
this.subscription = interval(1000).subscribe(() => this.seconds++);
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
}The interval observable never completes by itself. Without the unsubscribe() call, it would keep ticking after the component is removed.
The ?. operator matters here. If the component is destroyed before ngOnInit ran, subscription is still undefined, and calling unsubscribe() on it would throw.
What to release
Release anything that outlives the component's own template:
- RxJS subscriptions to observables that do not complete, such as
interval, a store, or afromEventstream. - Timers from
setTimeoutandsetInterval, usingclearTimeoutandclearInterval. - Listeners added with
addEventListener, usingremoveEventListenerwith the same function reference. - Connections such as WebSockets or
ResizeObserverinstances, using theirclose()ordisconnect()methods.
You do not need to unsubscribe from the async pipe. It cleans up on its own. Observables that complete, such as a single HttpClient request, also release themselves.
Several subscriptions
With many subscriptions, you can keep a single parent Subscription and add children to it. One unsubscribe() call then releases all of them.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, interval, fromEvent } from 'rxjs';
@Component({
selector: 'app-activity',
standalone: true,
template: `<p>Ticks: {{ ticks }}, clicks: {{ clicks }}</p>`,
})
export class ActivityComponent implements OnInit, OnDestroy {
ticks = 0;
clicks = 0;
private readonly subscriptions = new Subscription();
ngOnInit(): void {
this.subscriptions.add(interval(1000).subscribe(() => this.ticks++));
this.subscriptions.add(fromEvent(document, 'click').subscribe(() => this.clicks++));
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
}Common mistakes
- Forgetting to unsubscribe from a long-lived observable. Each time the component is created again, another subscription is added, and the leak grows.
- Passing a new function to
removeEventListener. It removes nothing, because the reference differs from the one you added. Store the handler in a property. - Starting async work in
ngOnDestroy. The component is already going away, so the work is not guaranteed to finish. - Skipping cleanup in directives. Directives have the same hook and the same leaks.
Exercise
A component calls window.addEventListener('resize', () => this.update()) in ngOnInit, and calls window.removeEventListener('resize', () => this.update()) in ngOnDestroy. The listener keeps firing after the component is destroyed. Why, and how do you fix it?
Show answer
The two arrow functions are different objects, so removeEventListener does not match the registered listener and removes nothing. Store the handler in a property, for example private onResize = () => this.update();, pass this.onResize to both addEventListener and removeEventListener.