0
0
Angularframework~3 mins

Why ngOnDestroy for cleanup in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could clean up its mess all by itself when you leave a page?

The Scenario

Imagine you create a component that listens to user actions or data streams. When you leave that component, you forget to stop those listeners or subscriptions.

The Problem

Without proper cleanup, your app keeps running old listeners in the background. This wastes memory, slows down your app, and can cause strange bugs that are hard to find.

The Solution

Angular's ngOnDestroy lets you run cleanup code automatically when a component is removed. This stops listeners and frees resources, keeping your app fast and bug-free.

Before vs After
Before
componentDidLeave() { /* forgot to unsubscribe from data stream */ }
After
ngOnDestroy() { this.subscription.unsubscribe(); }
What It Enables

You can build smooth, efficient apps that clean up after themselves without extra effort.

Real Life Example

Think of a chat app where each chat window listens for new messages. When you close a chat, ngOnDestroy stops the message listener so your app stays quick and responsive.

Key Takeaways

Manual cleanup is easy to forget and causes bugs.

ngOnDestroy runs cleanup code automatically.

This keeps your Angular app fast and reliable.