Tarun Patel
Tarun Patel

Reputation: 253

Trying to lazy load Angular Material related custom module for lazy loaded components using forRoot() doesn't work

I have a lazyloading modules setup through angular-routing , i am using angular-material package for rendering data. As recommended i have made a custom module for materail-components named MaterialModule (with a forRoot method) I import it in app-module as forRoot : MaterialModule.forRoot(), , however in my lazy-loaded components/modules this MaterialModule is not available unless i explicitly import it across all the lazy-loaded modules as well.

app-module.ts
imports: [
BrowserModule,
AppRoutingModule,
MaterialModule.forRoot(),
CoreModule]

=============

material-module.ts
export class MaterialModule {
  static forRoot(): ModuleWithProviders {
  return {
    ngModule: MaterialModule
   }
 }
}

Is there a way a shared-module (like this MaterialModule) can be made available across all the lazy-loaded modules in angular.

Upvotes: 1

Views: 1022

Answers (1)

J. S.
J. S.

Reputation: 2374

Nothing wrong here. Declarations of a module are only available when they are exported in a module and the module gets imported in another module where you want to use them, only the stuff in providers will be shared across your whole application.

Having a module with forRoot is just a convention to initialize things once, or to build a singleton pattern.

But if you want to use things from that module, you have to import it in every module where you need it, without forRoot of course.

That is all about the scope, providers have a global scope, which means it is visible everywhere. Declarations have a private scope, which means they are only visible inside the current module. If you want to use them elsewhere you need to export them in their own module and import that module in another module to use them.

Here is an article about ngModules it explains it more detailed: https://medium.com/@cyrilletuzi/understanding-angular-modules-ngmodule-and-their-scopes-81e4ed6f7407

When it comes to lazy loading it is the same, except that providers of lazy loaded modules are avaible only after the module has loaded.

Upvotes: 1

Related Questions