2016-09-02 87 views
6

目前我正在使用這段代碼動態加載一些組件。Angular 2:使用參數@Input和@Output動態加載組件

export class ComponentOutlet { 

    constructor(
     private vcRef: ViewContainerRef, 
     private compiler: Compiler, 
     private dataService: DataService 
    ) { } 

    private _createDynamicComponent() { 

     // Some logic to decide which component should be loaded 
     return MyComponent; 
    } 


    ngOnChanges() { 

     this.compiler.compileComponentAsync(this._createDynamicComponent()) 
      .then(factory => { 
       const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector); 
       this.vcRef.clear(); 
       this.vcRef.createComponent(factory, 0, injector); 
      }); 
    } 

的問題是,MyComponent有一些@InputOutput綁定。這裏可以設置這個綁定嗎?我怎樣才能做到這一點?

+0

隨着RC6 +現在有'.compileComponentAsync' ..點擊這裏一個選項http://stackoverflow.com/q/38888008/1679310 *(也與綁定輸入)* –

+0

@RadimKöhler'compileComponentAsync'在RC6中被刪除。使用RC6 +現在有'compileModuleAndAllComponentsAsync' – yurzui

+0

@yurzui,正確..這就是我所說的 –

回答

7

輸入和輸出的綁定只能用於靜態添加到其他組件模板的組件。

在你的情況,你可以做到這一點勢在必行像

var cmpRef = this.vcRef.createComponent(factory, 0, injector); 
cmpRef.instance.someInput = value; 
cmpRef.instance.someOutput.subscribe(data => this.data = data); 
+1

當添加輸入時,Angular觸發了ngOnChanges()實例嗎?對我而言,它並不是。我必須手動調用cmpRef.instance.ngOnChanges()。 –

+2

不,ngOnChanges()會在'someProp'改變時調用'[someInput] =「someProp」'。沒有這種綁定'ngOnChanges'將不會被調用。你可以讓'someInput'成爲一個setter,並把代碼放在那裏。 –

+0

@GünterZöchbauer在這種情況下,我們知道動態創建的組件的輸入,並將輸入作爲組件需求。那麼,如果我們根據參數創建不同的動態組件,並且每個動態組件需要不同的輸入?應該有一種系統的方法來將輸入參數從父母傳遞給孩子。 – omeralper