【问题标题】:How do you make an Angular 2 component destroy itself?如何让 Angular 2 组件自行销毁?
【发布时间】:2017-08-26 09:09:17
【问题描述】:

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

我正在使用viewContainerRef.createComponent 动态创建它们。模板如下所示:

<template item-host></template>

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

<template item-host [ERROR ->](destroyCheck)="someMethod($event)"></template>

【问题讨论】:

    标签: angular components


    【解决方案1】:

    使用 ComponentRef.destroy()

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

    父母:

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

    孩子:

    viewRef: ComponentRef<SOMECOMP>;
    ...
    this.viewRef.destroy();
    ...
    

    【讨论】:

    • 它工作正常。从建筑师/角度方法的角度来看可以吗?
    【解决方案2】:

    声明一个输出变量

    @Output() destroyCheck:EventEmitter<string>=new EventEmitter<string>();
    
    ngOnDestroy(){
    
              this.destroyCheck.emit('destroyed');
    
    }
    

    在你的父组件中这样处理。

    <div>
         <child-comp (destroyCheck)="someMethod($event)"> </child-comp>
    </div>
    

    你的方法应该被处理为

    someMethod(something){
      console.log(something);
    }
    

    【讨论】:

    • 这肯定会正常工作并且看起来不错。我正在使用&lt;template item-host&gt;&lt;/template&gt;,但它给出了错误。我更新了问题。
    • &lt;template&gt; 是默认的 html 标签,不能用于自定义组件。
    • 也许我遗漏了一些东西,但问题是如何销毁组件,答案显示如何在被销毁后通知父级(如何未回答)?
    猜你喜欢
    • 2016-12-05
    • 2019-07-28
    • 2018-11-12
    • 2021-04-26
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    相关资源
    最近更新 更多