2017-08-07 62 views
0

我有一個Angular4組件,只要用戶按下加號按鈕,就可以動態創建許多孩子。子組件有一個輸入選擇,必須在選項選擇後向父組件發送信息。正在ComponentFactoryResolver創建Angular4之間的孩子動態創建的組件之間的通信

兒童組件下面的部分

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent); 
let viewContainerRef = this.anchor.viewContainerRef; 
viewContainerRef.createComponent(componentFactory); 

子組件具有使用EventEmitter輸出,但什麼也沒有發生在應用程序運行時。

我試過沒有動態創建,工作正常。

我搜索了很多例子,但他們都沒有考慮angular4或父與動態創建子之間的通信。

+0

你能否爲你的問題創建一個重要的例子。找到解決方案將會很有幫助 –

回答

0

試試這個:

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent); 
let viewContainerRef = this.anchor.viewContainerRef; 
const dynamicComponentInstance = viewContainerRef .createComponent(componentFactory) 
      .instance; 
dynamicComponentInstance['childEventEmitter'].subscribe((eventEmitter) => { 
      console.log(eventEmitter) 
     }); 

「childEventEmitter」 是你的子組件發出一個變量名。