2015-11-03 49 views
14

我正在開發的應用程序Angular2動態插入,並且我面臨一個問題:Angular2:雙向數據上組件綁定使用DynamicComponentLoader

我有一組可以使用UI來選擇不同的對象。每個對象都有一組選項(對不同的對象不同),可以使用UI進行編輯。現在,我使用DynamicComponentLoader爲當前選定的對象插入特定組件,以便它可以正確處理其選項。 問題是我不知道如何將當前選定對象的數據綁定到動態插入的選項組件。

@Component({ 
    selector: 'dynamic', 
    template: `<div>Options:</div> 
      <div>Property1: <input type="number" /></div> 
      <div>Property2: <input type="text" /></div>` 
    // template: `<div>Options:</div> 
    //   <div>Property1: <input type="number" [(ng-model)]="currentSelection.property1" /></div> 
    //   <div>Property2: <input type="text" [(ng-model)]="currentSelection.property1" /></div>` 
}) 
class DynamicComponent { 

} 


@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Selected: {{currentSelection.name}}!</h2> 
     <div #container></div> 
    </div> 
    ` 
}) 
class App { 
    currentSelection = {name: 'Selection1', property1: 10, property2: 'test'}; 

    constructor(private loader: DynamicComponentLoader, private elementRef: ElementRef) { 
    loader.loadIntoLocation(DynamicComponent, elementRef, 'container'); 
    } 
} 

Here是plunker幫助你理解我的問題:

+1

是身邊有唯一的例子是這樣的https://github.com/angular/angular/blob/1aeafd31bd440a4997362e66738926387940fc1e/modules/angular2_material/src/components/dialog/dialog.ts –

回答

4

隨着angular2和Rxjs, 「Observables」 幾乎都是答案。

如果我理解正確你的問題,你需要讓你的DynamicComponent的「Observer」和你的容器「的Observable甚至更​​好Subject(如果您的容器需要訂閱其他觀察到的從收到的選擇)」。然後,加載您的動態組件後,訂閱它到您的容器。

只要您的容器上的選擇發生變化,就會將新選擇推送給您的訂戶。這樣,您可以加載多個動態組件,並且所有這些組件都將收到您的推送。

容器:

class App { 
    currentSelection = {}; 
    selections = [ 
    {name: 'Selection1', property1: 10, property2: 'test'}, 
    {name: 'Selection2', property1: 20, property2: 'test2'} 
    ]; 
    subject:Subject<any> = new Subject(); 

    constructor(private loader: DynamicComponentLoader, private elementRef: ElementRef) { 
    } 

    ngOnInit(){ 
    this.loader.loadIntoLocation(DynamicComponent, this.elementRef, 'container', this.injector) 
    .then(compRef =>this.subject.subscribe(compRef.instance)); 
    // subscribe after loading the dynamicComponent 
    } 

    // set the new selection and push it to subscribers 
    changeSelection(newSelection){ 
    this.currentSelection = newSelection; 
    this.subject.next(this.currentSelection); 
    } 
} 

觀察員:

class DynamicComponent implements Observer{ 
    public currentSelection = {}; 

    next(newSelection){ 
    this.currentSelection = newSelection; 
    } 
} 

這裏我的編輯後,你的工作plunker, 「提供我改變了進口最新的角beta.6」

我知道這是一個相當古老的問題。但希望有人會從這個答案中受益。

2

以下是您可以執行的操作,將代碼從constructor移動到ngOnInit,並使用承諾分配動態值。

ngOnInit(){ 
    this.dynamicComponentLoader.loadIntoLocation(DynamicComponent, this.elementRef,'container').then((component)=>{ 
     component.instance.currentSelection = currentSelection; 
    }); 
}