Sub topic 15
Checking for memory leaks with the Memory panel
A memory leak in an Angular app happens when objects you no longer need stay reachable, so the browser's garbage collector cannot free them. The usual symptom is a page that gets slower and heavier the longer someone uses it, especially after navigating between routes many times. This chapter shows how to confirm a leak with the Memory panel, find what holds the objects, and verify the fix.
This chapter assumes you can record a trace in the Performance panel, you know the component lifecycle (ngOnInit, ngOnDestroy), and you have used RxJS subscribe. Use a production-like build when you can, but keep source maps enabled so class names stay readable in snapshots.
What counts as a leak
The garbage collector frees an object when nothing reachable from a root (the window object, active timers, registered listeners) points to it. A leak is an object you consider dead that is still reachable. In Angular, the typical case is a destroyed component that something long-lived still references.
Growth alone does not prove a leak. Caches, loaded data, and lazy chunks legitimately increase memory. A leak is growth that repeats every time you do the same action and then undo it, such as opening and closing a page.
The three tools in the Memory panel
| Tool | What it records | Best for |
|---|---|---|
| Heap snapshot | All live objects at one moment | Finding which objects exist and what retains them |
| Allocation instrumentation on timeline | Allocations over time, with blue bars for objects still alive | Seeing when leaked objects are created |
| Allocation sampling | Statistical sample of allocation call stacks | Finding which functions allocate the most |
Heap snapshots are the main tool for leak hunting, so the rest of this chapter focuses on them.
Shallow size and retained size
Two columns in a snapshot confuse many learners at first.
- Shallow size is the memory held by the object itself, not counting what it points to.
- Retained size is the memory that would be freed if this object were deleted. It includes everything reachable only through it.
A destroyed component can have a small shallow size and a large retained size, because it keeps its view, its data, and its injected services alive. Sort by retained size to find the expensive holders first.
The three-snapshot technique
A single snapshot is hard to read because it contains the whole app. Comparing snapshots isolates what your action left behind.
Follow these steps:
- Open the app, navigate to the page you suspect, and go back once. This warm-up loads lazy chunks and fills caches, so they do not look like leaks.
- Open DevTools, go to the Memory panel, choose Heap snapshot, and click the trash can icon to force garbage collection. Take snapshot 1.
- Perform the suspect action, such as navigating to a route and away from it. Force garbage collection and take snapshot 2.
- Repeat the action and take snapshot 3.
- Select snapshot 3. In the dropdown above the table, choose Objects allocated between Snapshot 1 and Snapshot 2. Anything listed was created during the first round and is still alive after the second, which points strongly to a leak.
If the same class appears once per repetition, that is the signature. If your component class shows two instances after two rounds and three after three, it is leaking one per visit.
Finding the owner with the Retainers pane
Type your component's class name in the Class filter box, for example TickerComponent. Select an instance. The Retainers pane at the bottom shows the chain of references that keeps it alive. Read it from the bottom (the root) upward.
Common retainer chains in Angular apps:
- A
SubscriberorObservablewhose callback closure references the component. The closure is shown as acontextentry. - A
Windowevent listener whose handler referencesthis. - A
Timeoutor interval handle created bysetInterval. - A singleton service with an array or
Mapthat still contains the component or its data.
Distance and retained size help you prioritize. The shortest retaining path is usually the one to fix.
A leaking component
This component starts an interval and never stops it. Each visit creates a new subscription that keeps the destroyed component alive.
import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<p>Ticks: {{ ticks }}</p>`,
})
export class TickerComponent implements OnInit {
ticks = 0;
ngOnInit() {
interval(1000).subscribe(() => this.ticks++);
}
}After three visits, the class filter shows three TickerComponent instances. The retainers pane points through an arrow function closure to a Subscriber, then to the timer.
Fixing it
Tie the subscription to the component's lifetime. takeUntilDestroyed completes the stream when the component is destroyed. Call it in an injection context, such as a constructor or field initializer.
import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<p>Ticks: {{ ticks }}</p>`,
})
export class TickerComponent {
ticks = 0;
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(() => this.ticks++);
}
}For manual listeners, register cleanup with DestroyRef:
import { Component, DestroyRef, inject } from '@angular/core';
@Component({
selector: 'app-width-watcher',
template: `<p>Width: {{ width }}</p>`,
})
export class WidthWatcherComponent {
width = window.innerWidth;
constructor() {
const onResize = () => {
this.width = window.innerWidth;
};
window.addEventListener('resize', onResize);
inject(DestroyRef).onDestroy(() => {
window.removeEventListener('resize', onResize);
});
}
}The handler must be the same function reference in both calls. Passing a new arrow function to removeEventListener removes nothing, and the leak stays.
Detached DOM nodes
In the class filter, type Detached. Nodes shown as Detached <div> are removed from the page but still referenced by JavaScript. They often accompany a leaked component, because the component holds its elements. They can also come from code that stores an ElementRef or a DOM node in a service or a global array. Fix the holder, and the detached nodes disappear with it.
Verifying the fix
Repeat the three-snapshot procedure on the fixed build. A good result is that your component class no longer appears in the comparison view, or only one instance appears, which is the live page. Also check the totals at the top of each snapshot. After warm-up, the heap size should stay roughly flat across rounds, with some variation from normal allocation.
Note that this follows the same discipline as any other optimization: compare repeatable before-and-after measurements, using the same steps each time.
Common mistakes
- Taking only one snapshot and treating every large object as a leak.
- Skipping the warm-up, so lazy-loaded code counts as growth.
- Looking at shallow size when retained size shows the real cost.
- Fixing the symptom, such as setting a field to
null, instead of removing the reference chain shown in the Retainers pane. - Forgetting that
asyncpipe andtakeUntilDestroyedclean up automatically, while manualsubscribecalls andaddEventListenerdo not.
Exercise
After three open-and-close rounds of a dashboard route, the class filter shows three DashboardComponent instances, and the Retainers pane shows a Window event listener closure. What is the likely cause, and how do you fix and verify it?
Show answer
The component calls window.addEventListener and never removes it, so the listener's closure keeps each destroyed component alive. Keep the handler in a variable and call window.removeEventListener with the same reference in DestroyRef.onDestroy or ngOnDestroy. Verify by repeating the three-snapshot procedure with garbage collection before each snapshot. The comparison view should no longer show extra DashboardComponent instances.
Exercise
What is the difference between shallow size and retained size, and which should you sort by when looking for the most costly leaked object?
Show answer
Shallow size is the memory of the object itself. Retained size is the memory that would be freed if the object were deleted, including objects reachable only through it. Sort by retained size, because a small destroyed component can keep a large view and dataset alive.