Sub topic 9
Cleaning up with ngOnDestroy
This chapter assumes you can write a standalone Angular component, you know the order of constructor, ngOnChanges and ngOnInit, and you can create and unsubscribe an RxJS subscription. The chapter explains what ngOnDestroy is, which resources need cleanup, and where cleanup code goes wrong.
What ngOnDestroy does
ngOnDestroy is the last hook Angular calls on a component or directive. Angular calls it once, just before it destroys the instance and removes its view. Pipes and services can use it too. A service provided in a component's providers array is destroyed with that component.
A component is destroyed when any of these happens:
- A router navigation replaces it in a
<router-outlet>. - A structural block that contains it stops rendering, such as
@if,@foror*ngIf. - A dynamically created component is destroyed through its
ComponentRef, or its container is cleared. - The application itself is destroyed.
Angular removes its own bookkeeping, such as template bindings and the change detection links. It cannot know about anything you started yourself. Those resources stay alive after the component is gone. The component instance stays reachable through their callbacks, so the garbage collector cannot free it. This is a memory leak. Worse, the callbacks keep running against a component the user can no longer see.
What needs cleanup
Release anything that outlives a single change detection pass and is not owned by Angular:
| Resource | How to release it |
|---|---|
| Subscription to a long-lived observable (`interval`, `fromEvent`, a store, a WebSocket) | `unsubscribe()` |
| `setInterval` or `setTimeout` | `clearInterval()` or `clearTimeout()` |
| `addEventListener` on `window`, `document` or other elements outside the template | `removeEventListener()` with the same function reference |
| `ResizeObserver`, `IntersectionObserver`, `MutationObserver` | `disconnect()` |
| Third-party widgets such as charts and maps | The library's `destroy()` or `dispose()` method |
| In-flight `fetch` requests | `AbortController.abort()` |
Some things need no cleanup:
- Event bindings in your template, such as
(click)="save()", are removed with the view. - The
asyncpipe unsubscribes for you. HttpClientobservables emit once and complete, so there is nothing left to release. If the user leaves before the response arrives, the request is cancelled by unsubscribing, which you only need to do if you want that cancellation.- Observables that your own component creates and no one else holds, for example a
FormControl.valueChangeson a control owned by the component.
Use this rule of thumb. If the thing that produces events lives longer than the component, you must disconnect from it.
The classic pattern
Start the work in ngOnInit and stop it in ngOnDestroy. Keep a reference to whatever you need to stop.
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 ?. matters. If Angular destroys a component before ngOnInit ever ran, the field is still undefined. Cleanup code should tolerate resources that were never created.
Cleaning up several resources
Real components often hold more than one resource. Each one needs its own release call. For event listeners, store the handler in a field so that removeEventListener receives the same function reference that you added.
import { Component, ElementRef, OnDestroy, OnInit, inject } from '@angular/core';
@Component({
selector: 'app-resource-panel',
standalone: true,
template: `<p>Ticks: {{ ticks }} | Width: {{ width }}</p>`,
})
export class ResourcePanelComponent implements OnInit, OnDestroy {
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
ticks = 0;
width = 0;
private timerId?: ReturnType<typeof setInterval>;
private observer?: ResizeObserver;
private readonly onOnline = (): void => {
console.log('Network is back');
};
ngOnInit(): void {
this.timerId = setInterval(() => this.ticks++, 1000);
window.addEventListener('online', this.onOnline);
this.observer = new ResizeObserver((entries) => {
this.width = Math.round(entries[0].contentRect.width);
});
this.observer.observe(this.host.nativeElement);
}
ngOnDestroy(): void {
clearInterval(this.timerId);
window.removeEventListener('online', this.onOnline);
this.observer?.disconnect();
}
}Passing an arrow function directly to removeEventListener would silently do nothing, because it would be a different function object from the one you registered. This is a common source of leaks.
Many subscriptions: Subscription.add and destroy$
When a component has many subscriptions, you can group them. A Subscription can own others through add, and one unsubscribe() call stops them all.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, fromEvent, interval } from 'rxjs';
@Component({
selector: 'app-grouped',
standalone: true,
template: `<p>Ticks: {{ ticks }}, clicks: {{ clicks }}</p>`,
})
export class GroupedComponent 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();
}
}An older pattern uses a destroy$ subject with takeUntil. You call this.destroy$.next() and this.destroy$.complete() in ngOnDestroy, and each pipe ends with takeUntil(this.destroy$). It works, but it needs a field, a hook and a reminder on every pipe. The next chapter replaces it with DestroyRef and takeUntilDestroyed, which tie the lifetime to the component automatically.
Limits and gotchas
ngOnDestroy is not a reliable place for work that must finish.
- It is synchronous. Angular does not wait for a returned promise. If you start a save request there, Angular destroys the component anyway, and the request may or may not complete.
- It does not run when the tab closes. When the user closes the tab or reloads the page, the browser stops the page without a guarantee that Angular gets to run hooks. Use the
pagehideevent ornavigator.sendBeaconfor last-moment data. - Same-route navigation reuses the component. Going from
/users/1to/users/2normally keeps the same instance. Angular does not callngOnDestroy, so listen to the route parameters instead of assuming a fresh component. - Callbacks can arrive late. A response from a request you did not cancel can resolve after destruction. Unsubscribing or aborting prevents the callback from touching a dead component.
- Server-side rendering. Timers and listeners created during server rendering never see a browser tab close. A forgotten
setIntervalcan keep the server render from finishing, so cleanup matters on the server too. Keep browser-only work out of code that runs during server rendering. - Do not rely on the order between parent and child. Both get their hooks called during teardown, but your cleanup should not depend on which comes first.
Do not put logic in ngOnDestroy that needs the DOM to still be fully present, such as measuring layout. Release resources and nothing more.
Checking that cleanup works
You can verify a leak directly. Add a console.log in the callback of a suspected subscription, navigate away from the component, and watch the console. If the log keeps appearing after the component is gone, cleanup is missing. In a test, call fixture.destroy() and assert that the resource stopped, for example with jasmine.clock() or fake timers and a spy on the callback. Testing is covered in a later chapter.
Summary of the rules
- Anything you start that outlives the component must be stopped when the component is destroyed.
- Keep references to timers, observers and handler functions so that you can release them.
- Write cleanup defensively, because
ngOnInitmay not have run. - Do not do asynchronous or must-finish work in
ngOnDestroy.
Exercise
A component adds 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 function objects, so removeEventListener finds no matching listener and removes nothing. Store the handler in a field, for example private readonly onResize = (): void => this.update();, pass this.onResize to both addEventListener and removeEventListener.
Exercise
A user edits a form and navigates away. You put this.http.post('/api/draft', this.form.value).subscribe() in ngOnDestroy to save the draft. Name two reasons this is unreliable, and say what you would do instead.
Show answer
ngOnDestroy is synchronous and Angular does not wait for the request, and the hook does not run reliably when the user closes the tab or reloads. Save drafts as the user edits (for example with a debounced valueChanges subscription) or from a route guard, and use pagehide or navigator.sendBeacon for last-moment data.