我正在创建多个下拉菜单组件,父组件中有一个按钮,但我希望这些组件具有自行销毁的按钮。我敢肯定这很简单,但似乎找不到任何可以做到的事情。我知道如何从 parent 那里摧毁它,但似乎无法从内部做到这一点。有人知道吗?就在它被销毁之前,我怎样才能向 parent 发送消息让它知道呢? (我在父级中有它们的实例,但父级中还有其他需要信号的东西)
我正在使用 viewContainerRef.createComponent
动态创建它们。模板如下所示:
<template item-host></template>
我尝试了一个@Output 并得到了这个:
<template item-host [ERROR ->](destroyCheck)="someMethod($event)"></template>
最佳答案
使用 ComponentRef.destroy()
如果您使用 viewContainerRef.createComponent 动态创建组件,那么您可以使用 ComponentRef.destroy() 销毁它。您所需要的只是在组件中查看对自身的引用,如示例所示:
parent :
...
const componentRef = this.placeholder.createComponent(
this.resolver.resolveComponentFactory(SOMECOMP));
componentRef.instance.viewRef = componentRef;
...
child :
viewRef: ComponentRef<SOMECOMP>;
...
this.viewRef.destroy();
...
关于angular - 你如何让 Angular 2 组件 self 毁灭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151794/