2017-08-03 37 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上的子組件和嵌入視圖執行相同的操作。

更多信息請閱讀這些文章:

相關問題