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!
})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With