Angular2: Two-way data binding on component dynamically inserted using DynamicComponentLoader Angular2: Two-way data binding on component dynamically inserted using DynamicComponentLoader angular angular

Angular2: Two-way data binding on component dynamically inserted using DynamicComponentLoader


With angular2 and Rxjs, "Observables" are almost always the answer.

If i understood your problem correctly, you need to make your DynamicComponent an "Observer" and your container "an Observable or even better a Subject (In case your container needs to subscribe to another observable to receive selections from)". Then, after loading your dynamic component, subscribe it to your container.

Whenever the selection changes on your container, you push the new selection to your subscribers. This way, you can load multiple dynamic components and all will receive your pushes.

The Container:

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);  }}

The Observer:

class DynamicComponent implements Observer{  public currentSelection = {};  next(newSelection){    this.currentSelection = newSelection;  }}

Here is your plunker working after my edits, "provided I changed the imports to the newest angular beta.6"

I know this is a quite old question. But hopefully someone will benefit from this answer.


Here is what you can do, move your code from constructor to ngOnInit and use promises for assigning dynamic value.

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