Can component invoke a self destroy event

Sumit Agarwal picture Sumit Agarwal · Sep 29, 2016 · Viewed 29.7k times · Source

I have a parent component which opens a new component on click of a link, this new component is supposed to have a close button which on close sends a closing message to parent and destroy itself.

We can send the closing message using ngOnDestroy method, but how do I invoke the destroying of the child component.

<parent>
    <child></child> //child to be opened on click but close 
                    //event should be inside the child componenet
</parent>

Do correct me if i am having some conceptual mistake here. Thanks

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Sep 29, 2016

If you add a component using ViewContainerRef.createComponent() like shown in Angular 2 dynamic tabs with user-click chosen components, then the component can destroy itself when you pass cmpRef to the created component.

Otherwise I don't think there is a way. You can pass a value to the parent so that an *ngIf removes the component.

<child *ngIf="showChild" (close)="showChild = false"></child>
class ParentComponent {
  showChild:boolean = true;
}
class ChildComponent {
  @Output() close = new EventEmitter();

  onClose() {
    this.close.emit(null);
  }
}