Divneet
Divneet

Reputation: 718

Notification of destruction of a child component to a parent component

Is there a way that i can get to know if the child component was destroyed. I am aware of the ngOnDestroy lifecycle hook however my need is a little different.

I want the parent component to be informed if the child component was destroyed.

I already know that services can help or it can also be achieved via event emission. What i really want to know is that if there is a way which angular provides something like a flag that the component was destroyed or maybe a method that i could associate in order to extract this information.

Any help is highly appreciated!!

Upvotes: 0

Views: 2385

Answers (1)

Ricardo Rocha
Ricardo Rocha

Reputation: 16266

As @Eliseo in the comments sections pointed out, you can make your parent component bind an event from your child component that, when the child component is being destroy, notify the parent component throw that event.

As you can check the following example, the child component provides an event called beingDestroyed.The parent component is binding a function called childBeingDestroyedto the event beingDestroyed <<(beingDestroyed)=childBeingDestroyed()>>.

Parent component:

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


@Component({
  selector: 'parent',
  template: ` <h1>I'm a parent<h1>
              <button type="button" (click)="show=false">Click Me And I will destroy the child component!</button>
              <child *ngIf="show"
                 (beingDestroyed)=childBeingDestroyed()
              >
              </child>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class ParentComponent {
  show:boolean = true;

  childBeingDestroyed(): void{
    alert("Child Being Destroyed");
  }
}

Child component:

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


@Component({
  selector: 'child',
  template: ` <br><br>I'm a child<br>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class ChildComponent implements OnDestroy  {
  @Output() beingDestroyed = new EventEmitter<boolean>();
  ngOnDestroy(): void {
    this.beingDestroyed.emit();
  }
}

And in here, you can find a full working example of this concept.

Upvotes: 2

Related Questions