Memory leaks in Angular usually come from things that outlive the component: subscriptions, event listeners, timers and references held in long-lived services. 1. Unsubscribe from long-lived Observables HTTP calls complete on their own, but streams such as router events, form valueChanges, intervals, WebSocket feeds or store selections keep emitting. - Prefer the async pipe in templates; it unsubscribes automatically. - Use takeUntilDestroyed() (Angular 16+): constructor() { this.route.paramMap.pipe(takeUntilDestroyed()).subscribe(p => this.load(p.get('id'))); } - Convert to signals with toSignal(), which cleans up with the component. - In older code: a destroy$ Subject with takeUntil(this.destroy$), completed in ngOnDestroy. 2. Remove manual event listeners and timers - Prefer @HostListener or Renderer2.listen (which returns an unlisten function) over addEventListener. - Clear setInterval and setTimeout in ngOnDestroy, or use DestroyRef.onDestroy. - Disconnect ResizeObserver, IntersectionObserver and MutationObserver instances. 3. Clean up third-party libraries Chart, map and editor libraries often need explicit destroy() calls. 4. Watch long-lived services Singleton services that store component references, callbacks or ever-growing arrays and caches keep that memory forever. Limit cache sizes and remove entries when no longer needed. 5. Detached DOM and dynamic components Components created with ViewContainerRef.createComponent must be destroyed, and overlays or dialogs must be closed properly. How to find leaks - Chrome DevTools Memory panel: take a heap snapshot, navigate to a page and away several times, take another snapshot and compare. Look for growing numbers of component instances or detached DOM nodes, and inspect the retainers. - The Performance monitor shows JS heap size and DOM node count over time. - Angular DevTools helps see which components still exist. Prevention: code review rules (every subscribe has a clear teardown), lint rules such as rxjs-angular's prefer-takeuntil, and testing navigation-heavy flows.
Ravindra Wadile · · 0 likes