ngOnInit And ngOnDestroy In Angular

ngOnInit And ngOnDestroy In Angular

In this article, We will learn about the Angular ngOnInit and ngOnDestroy life cycle Hooks function. In the previous article, we learned about Angular lifecycle hooks. Let's look at the ngOnInit and ngOnDestroy hooks in this chapter.

ngOnInit

When a component is built for the first time, the ngOnInit or OnInit hook is called. This hook is called after the function constructor and the first ngOnChanges hook have been fired.

This is an excellent area to put any initialization logic for your component.

The ngOnChanges hook is called before the ngOnInit hook. When the ngOnInit hook is called, all of the input properties are available to use.

This hook is only used once.

Before any of the child directive properties are initialized, this hook is called.

ngOnDestroy

The ngOnDestroy or OnDestroy hook is called shortly before Angular destroys the Component/Directive instance.

Use this hook to perform any component cleanup logic. To avoid memory leaks, you should Unsubscribe Observables and detach event handlers here.

Example of ngOnInit

Let's make a component that shows how to use the OnInit and OnDestroy hooks.

Let's create a Child Component that is conditionally displayed or removed depending on the Parent Component's flag.

Child Component

Create the child.component.ts

First, import the angular/core library's OnDestroy and OnInit functions.

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

The title "Child Component" is all that is displayed in the Component template.
@Component({
  selector: 'child-component',
  template: `
      <h2>Child Component</h2>
      ` ,
  styleUrls: ['./app.component.css']
})

Declare a child component that implements the hooks OnInit and OnDestroy.
export class ChildComponent implements OnInit, OnDestroy {

}

When the constructor is called, add the constructor to the log.
constructor() {
    console.log('ChildComponent:Constructor');
}

Finally. To begin, create the hook method. The method creates a console log entry.
ngOnInit() {
  console.log('ChildComponent:OnInit');
}

ngOnDestroy() {
  console.log('ChildComponent:OnDestroy');
}

The code for the kid component in its entirety
import { Component, OnDestroy, OnInit } from '@angular/core';
 
@Component({
  selector: 'child-component',
  template: `
      <h2>Child Component</h2>
      ` ,
  styleUrls: ['./app.component.css']
})
export class ChildComponent implements OnInit, OnDestroy {
 
  constructor() {
    console.log('ChildComponent:Constructor');
  }
 
  ngOnInit() {
    console.log('ChildComponent:OnInit');
  }
 
  ngOnDestroy() {
    console.log('ChildComponent:OnDestroy');
  }
 
}

Parent Component

This is how our App Component appears.
import { Component, OnInit, OnDestroy } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
      <h2>Life Cycle Hook</h2>
      <button (click)="toggle()">Hide/Show Child </button>
      <child-component *ngIf="displayChild"></child-component>
      ` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
 
  displayChild = true;
 
  constructor() {
    console.log('AppComponent:Constructor');
  }
 
  toggle() {
    this.displayChild = !this.displayChild;
  }
 
  ngOnInit() {
    console.log('AppComponent:OnInit');
  }
 
 
  ngOnDestroy() {
    console.log('AppComponent:OnDestroy');
  }
}

It's worth noting that the parent template
template: `
      <h2>Life Cycle Hook</h2>
      <button (click)="toggle()">Hide/Show Child </button>
      <child-component *ngIf="displayChild"></child-component>

We've used the *ngIf directive, which hides or shows the child component depending on the value of the displaychild property. The toggle operation changes the displaychild's status.

OnInit and OnDestroy hooks have also been added to the parent component.

Now, run the application.

The following will appear in the console window when you run the code for the first time.
AppComponent: Constructor
AppComponent: OnInit
ChildComponent:Constructor
ChildComponent:OnInit

Toggle the switch on and off. The Child Component is removed, and the following logs appear.
ChildComponent:OnDestroy

Toggle the toggle button once more. The Child Component is re-created, and you'll notice that the constructor of the child component is called once more, followed by the OnInit method.
ChildComponent:Constructor
ChildComponent:OnInit

The code above shows how the OnInit and OnDestroy functions work.

Difference Between Constructor and ngOnInit

When a class is instantiated, the constructor is called. The angular has nothing to do with it. It's a Javascript feature, and Angular doesn't have any influence over it.

When Angular has initialized the component with all of its input properties, the ngOnInit method is invoked.

Under the ngOnInit lifecycle hook, the @Input properties are exposed. This will assist you with doing some initialization tasks, such as retrieving data from the back-end server and displaying it on the view.

Inside the constructor, input properties are marked as undefined.

Conclusion

OnInit Hook is used to initializing the component, such as obtaining data from the back-end server, whereas OnDestroy Hook is used to cleaning up the component.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post