Showing posts with label Angular takeUntilDestroyed. Show all posts
Showing posts with label Angular takeUntilDestroyed. Show all posts

Saturday, December 5, 2026

How to Fix Memory Leaks in Angular Applications: A Complete Developer's Guide

Learn how to identify, debug, and prevent memory leaks in Angular using RxJS, takeUntilDestroyed(), Async Pipe, and Chrome DevTools.


Have you ever noticed your Angular application becoming slower after users navigate between different pages several times? Maybe components take longer to load, browser memory keeps increasing, or the application suddenly becomes unresponsive.

One possible reason behind these problems is a memory leak.

Memory leaks are common in modern JavaScript applications, especially when developers work with Angular components, RxJS Observables, event listeners, and asynchronous operations. They usually occur when an application continues holding references to objects that are no longer needed.

The good news is that Angular provides several effective ways to prevent and fix memory leaks. In this guide, we will explore the most common causes of Angular memory leaks and practical solutions using real TypeScript code examples.

What Is a Memory Leak in Angular?

A memory leak happens when an application retains memory that it no longer needs. Instead of allowing the JavaScript garbage collector to release unused objects, some references continue keeping those objects alive.

In Angular, this commonly happens when a component is destroyed but its subscriptions, timers, or event listeners remain active.

For example, imagine a dashboard component subscribing to a real-time notification service. When users navigate away from the dashboard, Angular destroys the component. However, if the subscription remains active, it may continue processing events and retaining references to the destroyed component.

Over time, these unnecessary references can affect application performance.

1. Unsubscribe from RxJS Observables

One of the most common causes of memory leaks in Angular is failing to unsubscribe from long-running RxJS Observables.

Consider this example:

export class DashboardComponent implements OnInit {
  ngOnInit(): void {
    this.notificationService.notifications$.subscribe(
      (notification) => {
        console.log(notification);
      }
    );
  }
}

The problem is that the subscription is never cleaned up. If the Observable continues emitting values after the component is destroyed, the subscription can remain active.

Solution: Use takeUntilDestroyed()

Modern Angular provides the takeUntilDestroyed() operator, which automatically unsubscribes when the associated component or directive is destroyed.

import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-dashboard',
  template: '<h2>Dashboard</h2>'
})
export class DashboardComponent {
  private notificationService = inject(NotificationService);

  constructor() {
    this.notificationService.notifications$
      .pipe(takeUntilDestroyed())
      .subscribe((notification) => {
        console.log(notification);
      });
  }
}

This approach makes subscription management easier and reduces unnecessary cleanup code.

Why use this approach?

  • Automatically handles subscription cleanup.
  • Reduces repetitive unsubscribe logic.
  • Makes components easier to maintain.
  • Helps prevent common RxJS memory leaks.

Note that when calling takeUntilDestroyed() outside an injection context, pass an explicitly injected DestroyRef.

2. Use the Angular Async Pipe

Another effective way to prevent memory leaks is using Angular's built-in Async Pipe.

Instead of manually subscribing to an Observable inside your component, you can bind it directly to your template.

For example:

export class UserComponent {
  users$ = this.userService.getUsers();
}

In your HTML template:

HTML
Wrap linesCopy code
<div *ngIf="users$ | async as users">
  <div *ngFor="let user of users">
    {{ user.name }}
  </div>
</div>

The Async Pipe automatically subscribes to the Observable and unsubscribes when its view is destroyed or when the Observable reference changes.

This makes it an excellent option for displaying API responses, user information, and other asynchronous data.

Whenever possible, prefer the Async Pipe over manual subscriptions when your component only needs to display Observable data.

3. Clean Up Event Listeners

Event listeners attached to global objects such as window and document can also cause memory leaks.

For example:

ngOnInit(): void {
  window.addEventListener('resize', this.handleResize);
}

If you never remove the event listener, the browser may continue holding references to its callback.

Solution: Remove Event Listeners

Use ngOnDestroy() to remove manually registered listeners.

export class DashboardComponent implements OnInit, OnDestroy {

  handleResize = () => {
    console.log('Window resized');
  };

  ngOnInit(): void {
    window.addEventListener('resize', this.handleResize);
  }

  ngOnDestroy(): void {
    window.removeEventListener('resize', this.handleResize);
  }
}

An important detail is that removeEventListener() must receive the same callback reference used when registering the listener.

This simple cleanup practice helps prevent unnecessary event processing and retained references.

4. Clear setInterval() and setTimeout()

Timers are another frequently overlooked source of memory leaks.

For example, a component might use setInterval() to refresh dashboard information every few seconds.

ngOnInit(): void {
  setInterval(() => {
    this.loadDashboardData();
  }, 5000);
}

The timer can continue running even after the component has been destroyed.

Solution: Clear Timers During Component Destruction

Store the timer reference and clear it when the component is destroyed.

export class DashboardComponent implements OnInit, OnDestroy {

  private timerId: ReturnType<typeof setInterval> | undefined;

  ngOnInit(): void {
    this.timerId = setInterval(() => {
      this.loadDashboardData();
    }, 5000);
  }

  ngOnDestroy(): void {
    if (this.timerId !== undefined) {
      clearInterval(this.timerId);
    }
  }
}

Always clean up timers that are no longer required. This is particularly important for dashboards, polling mechanisms, and real-time applications.

5. Detect Memory Leaks Using Chrome DevTools

Fixing memory leaks starts with identifying where they occur. Chrome DevTools provides useful tools for inspecting JavaScript memory usage.

Follow these steps:

  1. Open your Angular application in Google Chrome.
  2. Open Chrome DevTools using F12.
  3. Navigate to the Memory tab.
  4. Select Heap Snapshot.
  5. Take an initial snapshot.
  6. Navigate between components or pages several times.
  7. Take another snapshot after the application has settled.
  8. Compare the snapshots to identify objects that remain in memory unexpectedly.

Pay attention to detached DOM elements, event listeners, and objects retained by subscriptions.

You can also use the Performance Monitor to observe JavaScript heap usage and the number of DOM nodes and event listeners.

Remember that increasing memory usage alone does not prove a memory leak. JavaScript garbage collection is not immediate, so compare snapshots after allowing garbage collection to run.

6. Follow Angular Memory Management Best Practices

Preventing memory leaks is easier than debugging them after deployment. Make cleanup part of your regular development workflow.

Here are some useful practices:

  • Use takeUntilDestroyed() for long-running Observable subscriptions.
  • Prefer the Async Pipe when displaying Observable data in templates.
  • Remove manually registered global event listeners.
  • Clear unnecessary intervals and timeouts.
  • Destroy third-party charting, mapping, and editor instances when components are destroyed.
  • Avoid storing unnecessary component references in singleton services.
  • Review subscriptions whenever you create or modify components.
  • Monitor application memory during development and testing.

Also remember that not every subscription is a memory leak. For example, Angular HttpClient Observables normally complete after receiving their response. The important thing is understanding whether a subscription can outlive the component that created it.

Conclusion

Memory leaks can gradually affect the performance, stability, and user experience of Angular applications. However, most common issues can be prevented with proper resource management and a consistent cleanup strategy.

Start by reviewing your RxJS subscriptions, using takeUntilDestroyed() and the Async Pipe wherever appropriate. Make sure global event listeners and timers are removed when components are destroyed, and use Chrome DevTools to investigate suspicious memory growth.

Building these practices into your Angular development workflow will help you create applications that remain responsive, maintainable, and reliable as they grow.

Remember: Good Angular performance is not just about writing faster code. It is also about knowing when to release resources that your application no longer needs.

B
BEING CODERS

Take Your Coding Journey Further!

Find more coding tutorials, technology insights, programming guides, and practical knowledge. Choose your reading experience below!

✦ Keep Learning. Keep Building. Keep Coding. ✦