2017-08-03 35 views
1

我试图通过其注入到构造函数私人compRef摧毁使用ComponentRef类组件:ComponentRef如何使用destroy()方法类的方法ComponentRef <C>

这是给错误:未捕获(承诺):错误:没有提供ComponentRef!

尝试在组件级和app.module中的providers数组中包含ComponentRef,但它表示类型ComponentRef不能用于键入'Providers'。

有关如何实施ComponentRef以便能够使用destroy()方法的任何帮助?

谢谢。

+0

参见[我的回答(https://stackoverflow.com/a/45474587/2545680)的说明的销毁方法。你为什么想要销毁一个组件? –

+0

@maximus,谢谢你的帮助。我将需要清除与该组件相关的所有属性和对象。我认为destroy()方法是一种快速而干净的方法。 – Venkat

+0

我明白了。 “摧毁”实际上并没有做你认为它做的事情。检查我更新的答案 –

回答

0

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如果它不是动态创建。

I will need to clear all the properties and objects related to that component.

destroy方法实际上不清除的组件实例的任何属性。它只是从视图容器或applicationRef分离视图,分离投影视图并更新视图组件的状态。它还触发destroy上的子组件和嵌入视图执行相同的操作。

更多信息请阅读这些文章:

相关问题