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


when creating components dynamically through componentfactory componentref that's returned provides destroy method works i'd accomplish. in mind, looks need componentref statically created component , use destroy function (which this answer states), when try error saying "destroy not function" though object back.

here's syntax i'm using viewchild:

@viewchild(mycomponent) mycomponentref: componentref<mycomponent>; 

and "destroy" call:

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

which triggered here:

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

calling "destroy" method works components create dynamically, not statically.

edit: so seems partially remove component, not dom, not same behavior occurs when calling "destroy" on dynamically created component. additionally, click event function still fires when click on component i've tried destroy.

edit 2: updated viewchild syntax explicitly read componentref , "undefined" back:

@viewchild(mycomponent, {read: componentref}) mycomponentref: componentref<mycomponent>; 

if returns "undefined" i'm guessing may not possible.

you can add *ngif in container of component , in base condition (ngif) perform destruction , creation of child element. example:

in view:

<div *ngif="destroy">     <component-child></component-child> </div> <button (click)="destroyfunction()">click destroy</button> 

in component parent class:

//declare view child @viewchild(componentchild) componentchild: componentchild;  //declare destroy variable destroy:boolean;  //add function change value of destroy (boolean) public destroyfunction(){     this.destroy = false; } 

performing these steps can perform destruction of child element. hope works effectively


Comments