2016-08-30 35 views
2

我使用this示例在我的應用程序中動態創建組件。在Angular 2.0中動態插入子組件訪問

export class App { 
    @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef; 
    private componentFactory: ComponentFactory<any>; 

    constructor(componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler) { 
    this.componentFactory = componentFactoryResolver.resolveComponentFactory(HelloComponent); 
    } 

    addItem() { 
    this.viewContainerRef.createComponent(this.componentFactory, 0); 
    } 
} 

這是問題。由於此組件作爲@ContentComponents進行跟蹤,我如何將數據注入此類組件?

我嘗試這樣的:

@ContentChildren(TextComponent) components: QueryList<TextComponent>; 

現在我成功地獲得了我TextComponent中的 QueryList然後我嘗試這樣:

this.components.forEach(x => x.Message = "Content component"); 

,並沒有什麼效果。

回答

1

這應做到:

addItem() { 
    var cmpRef = this.viewContainerRef.createComponent(this.componentFactory, 0); 
    cmpRef.instance.someProp = 'someValue'; 
    cmpRef.instance.someObservable.subscribe(val => this.val = val); 
    } 
+0

謝謝!有用。文檔中是否有任何反駁?我想閱讀關於ViewContainerRef和createComponent函數。 –

+1

僅限AFAIK https://angular.io/docs/ts/latest/api/core/index/ComponentFactoryResolver-class.html和https://angular.io/docs/ts/latest/api/core/index/ ViewContainerRef-class.html –