[英]How can I access child components values from a parent component when they are added dynamically?
[英]In Angular 5, how to get access to dynamically added child components from parent component?
我正在開發一個 Ionic + Angular 5 項目。
我需要動態加載一些組件。 按照 Angular 文檔中的動態組件加載器示例,我能夠成功加載組件並顯示它們。
但是,我需要能夠遍歷加載的組件。
在創建和銷毀子組件時,我可以輕松地在父組件中維護自己的組件列表,但在我看來,這很丑陋,而不是“角度方式”。
經過大量實驗和研究,似乎我無法使用 @ViewChildren 訪問動態添加的組件,因為它們有自己的視圖。 ViewChildren 未找到動態組件
這樣對嗎?
我可以使用 viewContainerRef.get() 遍歷子視圖並檢索 ViewRefs。 但是似乎沒有辦法在給定 ViewRef 的情況下獲得對組件的引用?
我注意到 ViewRef 的“rootNodes”屬性,但是該屬性沒有記錄在 Angular 文檔視圖參考中。但是,它記錄在 EmbeddedViewRef 文檔嵌入式視圖參考中,但似乎仍然沒有讓我訪問組件。
所以問題是當我有一個動態添加子組件的父級時,我如何從父級循環到子級組件(這樣我就可以在子級中調用我的方法之一)? 我懷疑是我遺漏了一些愚蠢的簡單東西,有一些根本的誤解,或者我應該使用不同的模式。
我修改了 Dynamic Component Loader 示例以突出顯示我正在嘗試做的事情。 修改后的動態組件加載器
所以,我想到了這一點,一個干凈的方法(在我看來)是在父組件上傳遞 create 一個屬性,例如parentContext
並將數據或方法傳遞給這個對象。
示例 - 在父組件中,您甚至可以將方法傳遞給子組件,它會在父組件的上下文中運行。 :
gotoDetail(hero: Hero): void {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(DynamicModalChildComponent);
this.dynamicModalComponentRef = this.entry.createComponent(factory);
this.dynamicModalComponentRef.instance.hero = hero;
// Pass parent context to child in order to close modal hierarchically (parent/child component relationship).
// This approach is less verbose and makes it easier to unit test than a service in my opinion.
this.dynamicModalComponentRef.instance.parentContext = () => this.destroyComponent();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.