Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you destroy an Angular 2 component without a ComponentFactory?

Tags:

angular

When creating components dynamically through a ComponentFactory the ComponentRef that's returned provides a destroy method which works perfectly for what I'd like to accomplish. With that in mind, it looks like all I need to do is a get a ComponentRef for a statically created component and then use its destroy function (which this answer states), but when I try this I get an error saying that "destroy is not a function" even though I do get an object back.

Here's the syntax I'm using for ViewChild:

@ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;

And my "destroy" call:

private destroy() {
    this.myComponentRef.destroy();
}

Which is triggered here:

<button (click)="destroy()">Destroy</button>

Calling this "destroy" method works for components that I create dynamically, but not statically.

Edit: So it seems like this does partially remove the component, but not from the DOM, which is not the same behavior that occurs when calling "destroy" on a dynamically created component. Additionally, my click event function still fires when I click on a component that I've tried to destroy.

Edit 2: I updated my ViewChild syntax to explicitly read for a ComponentRef and I get "undefined" back:

@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;

If that returns "undefined" then I'm guessing this may not be possible.

like image 913
badger2013 Avatar asked Sep 01 '16 22:09

badger2013


1 Answers

You can add a *ngIf in the container of your component and in a base to a condition (ngif) perform the destruction and creation of the child element. Example:

In the view:

<div *ngIf="destroy">
    <component-child></component-child>
</div>
<button (click)="destroyFunction()">Click to Destroy</button>

In the component parent class:

//Declare the view child
@ViewChild(componentChild) componentChild: componentChild;

//Declare the destroy variable
destroy:boolean;

//Add a function to change the value of destroy (boolean)
public destroyFunction(){
    this.destroy = false;
}

Performing these steps you can perform the destruction of the child element. I hope it works for you effectively

like image 55
jorghe94 Avatar answered Sep 24 '22 00:09

jorghe94