Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Destroy Current Component Completely

I tried searching google and stackoverflow but could not find an answer. So my question is simple "How can i remove current component in angular 2, 4"

example:

<div (click)="remove($event)">Remove Current Component</div>

remove($event) {
    // this.destroy() ????
}

Basically what i want is ComponentRef see this answer ngOnDestroy() which calls this.cmpRef.destroy() :

ngOnDestroy() {
   if(this.cmpRef) {
     this.cmpRef.destroy();
   }    
}

But he is getting the ComponentRef due to dynamically creating the component.

like image 704
Touqeer Shafi Avatar asked Aug 24 '17 07:08

Touqeer Shafi


People also ask

Does angular router destroy component?

So, basically Router in Angular 2 destroys inactive components (my tabs!).

How do you destroy a component in itself?

Forcing a Component to Destroy Itself. To make a component destroy itself when the user navigates away from it, you have to make the component call its ngOnDestroy() lifecycle hook when the page unloads. This is done by leveraging the host page's life cycle.

How do you destroy the current component in angular 6?

In our dynamic component loader, it will be load component using createComponent() of ViewContainerRef. The ComponentRef of the newly created component and call the clear() method of ViewContainerRef destroys the existing view in the container.

How do you destroy a child component?

child components from parent can be destroyed using reference of child component in parent component. this. dataArray = []; this.


1 Answers

You can use a *ngIf="myBoolean" directive on the component element in the parent template. When myBoolean becomes false, the component will be destroyed.

No more component or DOM element present. (and ngOnDestroy event raised)

If myBoolean becomes true again, a new component will be instantiated.

A new one will appear in DOM (and ngOnInit event raised)

Your click event can emit an event (binded in the parent with the (myEventEmitter) syntax, and a method in the parent component can then just set the boolean to false.

Demonstration on this Plunker. If it doesn't suit your need, consider editing your question to provide more specific details, including a Minimal Complete Verifiable example

like image 184
Pac0 Avatar answered Sep 28 '22 23:09

Pac0