angular - How can I create a component from a module that's already been imported? -
i have modal service that's responsible opening modal dialog on fly signature create<t>(component: type<t>, params?: object, module: type<{}> = appmodule): observable<componentref<t>>
. modal service meant problem when import module that's been imported, receive error unexpected value 'undefined' declared module 'mymodule'
. research shows common problem when attempting import things twice.
modalservice -
import { injectable, componentref, componentfactoryresolver, viewcontainerref, reflectiveinjector, injector, compiler, type } '@angular/core'; import { observable, replaysubject } 'rxjs'; import { appmodule } '../../app.module'; @injectable() export class modalservice { vcref: viewcontainerref; constructor(private componentfactoryresolver: componentfactoryresolver, private compiler: compiler, private injector: injector) { } registerviewcontainerref(vcref: viewcontainerref): void { this.vcref = vcref; } create<t>(component: type<t>, params?: object, module: type<{}> = appmodule): observable<componentref<t>> { let componentref$ = new replaysubject(); this.compiler.compilemoduleandallcomponentsasync(module) .then(factory => { let componentfactory = factory.componentfactories .filter(item => item.componenttype === component)[0]; const childinjector = reflectiveinjector.resolveandcreate([], this.injector) let componentref = this.vcref.createcomponent(componentfactory, 0, childinjector); object.assign(componentref.instance, params); componentref$.next(componentref); componentref$.complete(); }); return <observable<componentref<t>>> componentref$.asobservable(); } }
usage snippet when trying open modal dialog component foocomponent
belongs mymodule
.
import { mymodule } '../my.module'; this.modalservice.create(foocomponent, {}, mymodule)
based on documentation, module required when creating components if lazily loaded.
my question is, how can create components belongs module, loaded or not.
edit! works if component i'm dynamically creating not have dependencies, not happen often.
see plunker here. places i'm having issues files app/core/modal/modal.service.ts
, app/crisis-center/crisis-list.component.ts
(line 54 - modal should open). error that's showing uncaught (in promise): error: no provider myservice!
. not sure why since i'm creating component module myservice
defined provider.
is there perhaps better approach of accomplishing this?
tl;dr goal create service (modalservice
in case) component can create no matter module belongs to. obviously, needs support di.
Comments
Post a Comment