Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading dynamic module from another url- angular4

Is it possible to reference a module (already compile in umd or es format) and load it dynamically in a already compiled angular application?

  1. Main shell application hosted at: http://plugin_shell.mydomain.com
  2. A module (with a bunch of components, services, etc): compiled code is hosted at another url. let say: http://plugins/modules/myfirstplugin.umd.js
  3. When shell load. Load all modules, render specific components, refer to services, use class etc.

I tried to load the module with SystemJsNgModuleLoader.load, but it does seem to work with this kind of use cases.

Thanks

EDIT: Same question (no answer): How to dynamically load external angular 2 module (like served from an external module.bundle.js)

like image 503
ThePainnn Avatar asked Aug 08 '17 14:08

ThePainnn


1 Answers

You can do it like this:

@Component({
  providers: [
    {
      provide: NgModuleFactoryLoader,
      useClass: SystemJsNgModuleLoader
    }
  ]
})
export class ModuleLoaderComponent {
  constructor(private _injector: Injector,
              private loader: NgModuleFactoryLoader) {
  }

  ngAfterViewInit() {
    this.loader.load('app/t.module#TModule').then((factory) => {
      const module = factory.create(this._injector);
      const r = module.componentFactoryResolver;
      const cmpFactory = r.resolveComponentFactory(AComponent);

      // create a component and attach it to the view
      const componentRef = cmpFactory.create(this._injector);
      this.container.insert(componentRef.hostView);
    })
  }
}

Read Here is what you need to know about dynamic components in Angular for more details. Specifically Dynamic module loading and compilation section.

like image 137
Max Koretskyi Avatar answered Oct 29 '22 10:10

Max Koretskyi