通过ComponentFactory动态创建组件时,返回的ComponentRef提供了一个destroy方法,该方法非常适合我想要完成的任务。考虑到这一点,看起来我需要做的就是为静态创建的组件获取ComponentRef,然后使用其destroy函数(this answer个状态),但是当我尝试这个时,我得到一个错误,说明“破坏不是一种功能”,即使我确实得到一个物体。
这是我用于ViewChild的语法:
@ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;
我的“破坏”电话:
private destroy() {
this.myComponentRef.destroy();
}
这是在这里触发的:
<button (click)="destroy()">Destroy</button>
调用此“destroy”方法适用于我动态创建但不是静态创建的组件。
编辑:所以看起来这部分删除了组件,但不是来自DOM,这与在动态创建的组件上调用“destroy”时发生的行为不同。此外,当我点击我试图销毁的组件时,我的点击事件功能仍会触发。
编辑2:我更新了我的ViewChild语法,以显式读取ComponentRef并返回“undefined”:
@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;
如果返回“未定义”,那么我猜这可能是不可能的。
答案 0 :(得分: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;
}
执行这些步骤可以执行子元素的销毁。我希望它能有效地为你服务