没有ComponentFactory的情况下如何销毁Angular 2组件? [英] How do you destroy an Angular 2 component without a ComponentFactory?

查看:62
本文介绍了没有ComponentFactory的情况下如何销毁Angular 2组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过ComponentFactory动态创建组件时,返回的ComponentRef提供了 destroy 方法,非常适合我想要完成的工作.考虑到这一点,看来我要做的就是为静态创建的组件获取ComponentRef,然后使用其destroy函数(

When creating components dynamically through a ComponentFactory the ComponentRef that's returned provides a destroy method which works perfectly for what I'd like to accomplish. With that in mind, it looks like all I need to do is a get a ComponentRef for a statically created component and then use its destroy function (which this answer states), but when I try this I get an error saying that "destroy is not a function" even though I do get an object back.

这是我用于ViewChild的语法:

Here's the syntax I'm using for ViewChild:

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

还有我的破坏"电话:

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

此处触发了哪个

<button (click)="destroy()">Destroy</button>

调用此销毁"方法适用于我动态创建而不是静态创建的组件.

Calling this "destroy" method works for components that I create dynamically, but not statically.

因此,这似乎部分删除了组件,但未从DOM中删除,这与在动态创建的组件上调用销毁"时发生的行为不同.此外,当我单击尝试破坏的组件时,单击事件功能仍会触发.

我更新了ViewChild语法以显式读取ComponentRef,然后返回未定义":

Edit 2: I updated my ViewChild syntax to explicitly read for a ComponentRef and I get "undefined" back:

@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;

如果返回"undefined",那么我猜这可能是不可能的.

If that returns "undefined" then I'm guessing this may not be possible.

推荐答案

您可以在组件的容器中并在条件(ngif)的基础中添加* ngIf来执行销毁和创建子元素的操作.示例:

You can add a *ngIf in the container of your component and in a base to a condition (ngif) perform the destruction and creation of the child element. Example:

在视图中:

<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;
}

执行这些步骤,即可破坏子元素.希望它能为您有效

Performing these steps you can perform the destruction of the child element. I hope it works for you effectively

这篇关于没有ComponentFactory的情况下如何销毁Angular 2组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆