我试图通过使用ComponentRef类将组件作为私有compRef注入到构造函数中来销毁组件:
它给出了错误:未捕获(承诺):错误:没有ComponentRef的提供程序!
尝试在组件级别和app.module的providers数组中包括ComponentRef,但是它说ComponentRef类型不能分配给类型“ Providers”。
关于如何实现ComponentRef以便能够使用destroy()方法的任何帮助吗?
谢谢。
destroy()
方法可以在动态创建的组件上调用。这是简单的示例:
export class SampleComponent implements AfterViewInit {
@ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
ngAfterViewInit() {
const componentFactory = this.resolver.resolveComponentFactory(BComponent)
const componentRef = this.vc.createComponent(componentFactory);
componentRef.destroy(); <-------------------
}
}
你不能访问的componentRef
,如果它不是动态创建的组件。
我将需要清除与该组件相关的所有属性和对象。
该destroy
方法实际上不会清除组件实例上的任何属性。它只是从视图容器中分离视图,或applicationRef
,从投影视图中分离并更新视图组件的状态。它还触发destroy
执行相同操作集的子组件和嵌入式视图。
阅读这些文章以获取更多信息:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句