Angular 2 dynamically loaded component, events do not fire?

I used Angular2 dynamic component loader. Everything works well.

My dynamically loaded component emits events, but I cannot 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: (thanks Gunther) *

 cmp.instance['somecustomevent'].subscribe(ev => { this.consoleLog(ev) // run function in parent! }) 
+5
source share
1 answer
  • LoadAsRoot does not trigger change detection

Currently, loadAsRoot() used only to load the root component ( AppComponent ), and inputs are not supported in the root component.

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

when using loadAsRoot you need to initiate change detection and manually connect the inputs, outputs, injector and component layout 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 null for DynamicComponentLoader

+6
source

Source: https://habr.com/ru/post/1246464/


All Articles