如何在没有ComponentFactory的情况下销毁Angular 2组件?

15
通过ComponentFactory动态创建组件时,返回的ComponentRef提供了一个完美实现我想要完成的destroy方法。考虑到这一点,看起来我所需要做的就是获取静态创建组件的ComponentRef,然后使用它的destroy函数(this answer中所述),但是当我尝试这样做时,我会收到一个错误,即“destroy不是一个函数”,尽管我确实得到了一个对象。

这是我在ViewChild中使用的语法:

@ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;

我的“destroy”调用:

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

这是在这里触发的:
<button (click)="destroy()">Destroy</button>

调用这个“destroy”方法对于我动态创建的组件有效,但对于静态创建的组件无效。
编辑:因此,似乎这部分删除了组件,但未从DOM中删除,这与在动态创建的组件上调用“destroy”时发生的行为不同。此外,当我单击尝试销毁的组件时,我的单击事件函数仍然会触发。
编辑2:我更新了我的ViewChild语法,明确地读取ComponentRef,但返回“undefined”:
@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;

如果返回值为“undefined”,那么我猜可能不可能实现。

你可以使用 *ngIf 指令来动态移除组件吗? - Julia Passynkova
这是Angular组件生命周期钩子页面https://angular.io/guide/lifecycle-hooks @badger2013你用过哪些资源来查找ComponentFactory的文档?https://medium.com/@Carmichaelize/angular-2-component-factory-resolver-395acb7c2129 - 这对我来说是新的。 - JGFMK
利用 https://angular.io/api/core/OnDestroy。 - JGFMK
1个回答

1
你可以在组件的容器中添加 *ngIf,并基于条件(ngif)执行子元素的销毁和创建。例如:
在视图中:
<div *ngIf="destroy">
    <component-child></component-child>
</div>
<button (click)="destroyFunction()">Click to Destroy</button>

在组件的父类中:
//Declare the view child
@ViewChild(componentChild) componentChild: componentChild;

//Declare the destroy variable
destroy:boolean;

//Add a function to change the value of destroy (boolean)
public destroyFunction(){
    this.destroy = false;
}

通过执行这些步骤,您可以销毁子元素。希望对您有效。


1
我添加了*ngIf,而不是一个属性,我创建了一个方法,我的ngIf在组件标签上而不是div上。我的组件在mat-tabs中。当切换选项卡时,我通过我的函数相应地设置ngIf。但是当回到选项卡时,我可以看到旧的结果。这种方式似乎没有销毁组件。 - muhammad kashif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接