【发布时间】:2017-01-09 22:20:45
【问题描述】:
当通过 ComponentFactory 动态创建组件时,返回的 ComponentRef 提供了一个 destroy 方法,该方法非常适合我想要完成的工作。考虑到这一点,看起来我需要做的就是为静态创建的组件获取一个 ComponentRef,然后使用它的销毁函数(this answer 状态),但是当我尝试这个时,我得到一个错误,说“销毁不是函数”,即使我确实得到了一个对象。
这是我用于 ViewChild 的语法:
@ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;
还有我的“毁灭”号召:
private destroy() {
this.myComponentRef.destroy();
}
这里触发:
<button (click)="destroy()">Destroy</button>
调用这个“销毁”方法适用于我动态创建的组件,但不是静态的。
编辑:所以看起来这确实部分删除了组件,但没有从 DOM 中删除,这与在动态创建的组件上调用“destroy”时发生的行为不同。此外,当我点击我试图销毁的组件时,我的点击事件函数仍然会触发。
编辑 2:我更新了 ViewChild 语法以显式读取 ComponentRef 并得到“未定义”返回:
@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;
如果返回“未定义”,那么我猜这可能是不可能的。
【问题讨论】:
-
你可以使用 *ngIf 指令动态删除组件吗?
-
这里是 Angular 组件生命周期钩子页面 angular.io/guide/lifecycle-hooks @badger2013 您使用哪些资源来查找有关 ComponentFactory 的文档? medium.com/@Carmichaelize/… - 对我来说是新的。
标签: angular