Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 dynamic loaded component, events not firing back?

I used Angular2 Dynamic Component Loader. All is working well.

My dynamically loaded component emits events, but I can't catch it anywhere.

Parent code:

this.dcl.loadAsRoot(SomeComponent, "#dynamiccomponenthere", this.injector)

Parent template:

<div id="dynamiccomponenthere" (somecustomevent)="someFunc()"></div>

Child:

...
this.somecustomevent.emit(data)
...

*SOLUTION: (thx Gunther) *

cmp.instance['somecustomevent'].subscribe(ev => {
    this.consoleLog(ev) // run function in parent!
})
like image 980
Teddy Avatar asked Apr 05 '16 12:04

Teddy


1 Answers

  • LoadAsRoot doesn't invoke change detection

Currently loadAsRoot() is only used to bootstrap the root component (AppComponent) and inputs aren't supported on the root component.

A workaround is explained in this comment https://github.com/angular/angular/issues/6370#issuecomment-193896657

when using loadAsRoot you need to trigger change detection and manually wire up Inputs, Outputs, Injector, and the component dispose function

function onYourComponentDispose() {
}
let el = this.elementRef
let reuseInjectorOrCreateNewOne = this.injector;
this.componentLoader.loadAsRoot(YourComponent, this.elementRef, reuseInjectorOrCreateNewOne, onYourComponentDispose)
.then((compRef: ComponentRef) => {
  // manually include Inputs
  compRef.instance['myInputValue'] = {res: 'randomDataFromParent'};
  // manually include Outputs
  compRef.instance['myOutputValue'].subscribe(this.parentObserver)
  // trigger change detection
  cmpRef.location.internalElement.parentView.changeDetector.ref.detectChanges()
  // always return in a promise
  return compRef
});

See also @ContentChild is null for DynamicComponentLoader

like image 199
Günter Zöchbauer Avatar answered Nov 15 '22 05:11

Günter Zöchbauer