Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make an Angular 2 component destroy itself?

I am creating multiple dropdown menu components with a button in the parent, but I want those components to have buttons which destroy themselves. I'm sure it's simple, but can't seem to find anything that will do it. I know how to destroy it from the parent, but can't seem to do it from within. Anyone know? And just before it's destroyed, how can I send a message to the parent letting it know? (I have instances of them in the parent, but there are other things in the parent that need a signal)

I'm creating them dynamically using viewContainerRef.createComponent. Template looks like this:

<template item-host></template>

I tried an @Output and got this:

<template item-host [ERROR ->](destroyCheck)="someMethod($event)"></template>
like image 940
Jus10 Avatar asked Dec 24 '22 19:12

Jus10


1 Answers

use ComponentRef.destroy()

if you creating components dynamically using viewContainerRef.createComponent then you can destroy it with ComponentRef.destroy(). all you need is view reference to itself in the component, like in the example :

parent:

...
const componentRef = this.placeholder.createComponent(
  this.resolver.resolveComponentFactory(SOMECOMP));
componentRef.instance.viewRef = componentRef;
...

child:

viewRef: ComponentRef<SOMECOMP>;
...
this.viewRef.destroy();
...
like image 191
Igor Zinin Avatar answered Dec 28 '22 10:12

Igor Zinin