1

Following a great article on dynamic component loading:

https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e

I want to know more about the use of System.import. The author uses a following syntax to load the javascript file of the module to be dynamically loaded.

System.import('../module1.module.js').then((module) => {
          this.compiler.compileModuleAndAllComponentsAsync(module.Module1Module)
              .then((compiled) => {
                  const factory = compiled.componentFactories[0];
                  this.container.createComponent(factory);
              });
      });

I understand that system.import is used to dynamically load modules at run time.

And in our case, we provide the name of the ts of the module file but because the js file will be also of same name we can provide that in the parameters of import function.

But I was wondering if we could provide a generic JS file in the parameter which not necessarily contains that module but more modules and components also. (These modules can come from other external projects/libraries) And then we can provide one of the module name like following and create components.

System.import('../main-app1.js').then((module) => {
          this.compiler.compileModuleAndAllComponentsAsync(module.Module1Module)
              .then((compiled) => {
                  const factory = compiled.componentFactories[0];
                  this.container.createComponent(factory);
              });
      });

I have tried above approach but it does not works for me.It fails at run time.

core.js:9110 ERROR Error: Uncaught (in promise): Error: No NgModule metadata found for 'undefined'.
Error: No NgModule metadata found for 'undefined'.
Deep
  • 929
  • 2
  • 16
  • 32

1 Answers1

1

So, I will summarize my findings such that it may help someone in future:

  • First, yes we can provide a generic JS file in the parameter of System.import.

It is because of the fact that System.import is not an angular thing but javascript/es feature.

It does not say that you can only provide an angular module js (which I had a wrong understanding prior) but a generic js file also.

  • Now the reason why I was getting the error was due to a dumb mistake that the js I was passing as a parameter did not contained the definition of the module.It was compiled without the reference of the module which I was trying to load.

In short, the module was not present in the JS file. So make sure to open the js file and check whether the module is present and you have not mistakenly forgotten to include the module in the js .

Deep
  • 929
  • 2
  • 16
  • 32