Home Angular Tutorials How to use ngOnDestroy lifecycle hook in Angular ?

How to use ngOnDestroy lifecycle hook in Angular ?

by aouidane.med.amine
230,227 views 10 min read

In this tutorial , we are going to learn how to implement ngOnDestroy lifecycle hook in angular and how to prevent memory leaks using it.

Also , we are going to see some differences between ngOnDestroy and ngOnInit lifecycle hook.

Table of Contents

Angular Lifecycle Hooks

Angular has 8 lifecycle hooks, but in this tutorial, we will see only the ngOnDestroy lifecycle hook

What is ngOnDestroy lifecycle hook ?

The ngOnDestroy lifecycle hook is a simple method that is called just before Angular destroys a component or a directive. 

This lifecycle hook represents the best place to perform any clean up tasks, such as unsubscribing from observables or detaching event handlers to prevent memory leaks.

ngOnDestroy Syntax

The ngOnDestroy hook is a function that is defined on a component or directive class.

The basic syntax for using the ngOnDestroy hook is as follows:

				
					import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnDestroy {

  ngOnDestroy() {
    // Clean up any state or memory that the component is holding onto
  }

}
				
			

It’s important to know that the ngOnDestroy lifecycle hook is only called just before the directive or component is destroyed, so it’s not called on every change detection cycle like many other lifecycle hooks such as ngDoCheck , ngOnChanges ..

How to Prevent memory leaks using ngOnDestroy lifecycle hook ?

The regular use for the ngOnDestroy lifecycle hook in angular is to prevent memory leaks by cleaning up subscriptions to observables or event handlers.

 This is very relevant in Angular applications because, unlike some other frameworks, Angular does not automatically clean up subscriptions when a component is destroyed.

For example, if a component subscribes to an observable in the ngOnInit lifecycle hook and doesn’t unsubscribe from that observable, the subscription will remain active until the application is closed

This can cause memory leaks and performance issues if the component is used frequently in the application.

To prevent this, we can use the ngOnDestroy lifecycle hook to unsubscribe from any subscriptions that are no longer needed.

ngOnDestroy lifecycle hook Example

Here is an example of how you might use the ngOnDestroy lifecycle hook in a component :

				
					import { OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

export class MyComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit() {
    // Subscribe to an observable that emits data periodically.
    myObservable.pipe(takeUntil(this.destroy$)).subscribe(data => {
      // Do something with the data.
    });
  }

  ngOnDestroy() {
    // Unsubscribe from the observable to prevent memory leaks.
    this.destroy$.next();
    this.destroy$.complete();
  }
}
				
			

In this example, the component subscribes to an observable that emits data periodically.

When the component is destroyed, the ngOnDestroy function is called, which unsubscribes from the observable and completes the destroy$ subject to prevent memory leaks.

The ngOnDestroy method is called automatically by Angular,

so you don’t need to call it yourself. You can put any cleanup logic that you need in this method.

ngOnDestroy vs ngOnInit lifecycle hook

ngOnDestroy lifecycle hook and ngOnInit lifecycle hook are both lifecycle hooks in Angular, and they are called at different times in the lifecycle of a component.

ngOnDestroy is called just before a component is destroyed.

This is a good place to perform any clean up tasks that are needed, such as canceling any outstanding network requests or unsubscribing from observables.

ngOnInit on the other hand, is called after a component has been initialized and its data-bound properties are available for use.

This is a good place to perform any additional setup that is required for the component, such as fetching initial data from a server.

In general, it’s best to use ngOnInit for any initialization logic that you want to run when a component is created, and use ngOnDestroy for any clean up tasks that need to be performed just before the component is destroyed.

References

Recapitulation

You may also like