ConorJohn ConorJohn - 3 months ago 25
TypeScript Question

Pass data from dynamicallyloadedcomponent back to parent page Angular2

I'm wondering if there is any way to pass data back from a dynamically loaded component in Angular2. I pass the component data using

this._dcl.loadIntoLocation(...).then(component => {
component.instance.variable = this.variable;
}


On completing the tasks inside the component, in my case a modal, can I pass data or variables back out in a similar manner? Thanks in advance.

Answer

You can add an Observable to the dynamically added component
(an EventEmitter might work as well but might break eventually. Then Angular2 team doesn't guarantee that an EventEmitter will keep behaving like an observable)

Then just subscribe to this observable

this._dcl.loadIntoLocation(...).then(component => {
  component.instance.variable = this.variable;
  component.instance.someObservable.subscribe(val => this.someVal = val);
}

DynamicComponentLoader is deprecated and AFAIK was already removed in master.

See also Angular 2 dynamic tabs with user-click chosen components