你如何让 Angular 2 组件自我毁灭?

Jus*_*s10 4 components angular

我正在创建多个带有父级按钮的下拉菜单组件,但我希望这些组件具有可自行销毁的按钮。我相信这很简单,但似乎找不到任何可以做到的东西。我知道如何从父母那里摧毁它,但似乎无法从内部做到这一点。有人知道吗?就在它被销毁之前,我如何向父母发送消息让它知道?(我在父级中有它们的实例,但是父级中有其他需要信号的东西)

我正在使用viewContainerRef.createComponent. 模板如下所示:

<template item-host></template>
Run Code Online (Sandbox Code Playgroud)

我尝试了一个@Output 并得到了这个:

<template item-host [ERROR ->](destroyCheck)="someMethod($event)"></template>
Run Code Online (Sandbox Code Playgroud)

小智 6

使用 ComponentRef.destroy()

如果您使用 viewContainerRef.createComponent 动态创建组件,那么您可以使用 ComponentRef.destroy() 销毁它。您所需要的只是在组件中查看对自身的引用,就像在示例中一样:

家长:

...
const componentRef = this.placeholder.createComponent(
  this.resolver.resolveComponentFactory(SOMECOMP));
componentRef.instance.viewRef = componentRef;
...
Run Code Online (Sandbox Code Playgroud)

孩子:

viewRef: ComponentRef<SOMECOMP>;
...
this.viewRef.destroy();
...
Run Code Online (Sandbox Code Playgroud)


Ara*_*ind 4

声明输出变量

@Output() destroyCheck:EventEmitter<string>=new EventEmitter<string>();

ngOnDestroy(){

          this.destroyCheck.emit('destroyed');

}
Run Code Online (Sandbox Code Playgroud)

在你的父组件中以这种方式处理。

<div>
     <child-comp (destroyCheck)="someMethod($event)"> </child-comp>
</div>
Run Code Online (Sandbox Code Playgroud)

你的方法应该被处理为

someMethod(something){
  console.log(something);
}
Run Code Online (Sandbox Code Playgroud)