Kazi
Kazi

Reputation: 1553

In angular, why do i have to import Material-modules Separately for different custom modules?

In my apps, I have several modules and few of them are implemented by lazy loading. For the lazy module, I have seen that I have to import MatButtonModule(and other modules as well) in their respective customs.module.js file even though they are already imported in the app.module.js.

My question is: for lazy loading is it the only way or there is any smarter way in which I just have to import the material modules once and will work for all the customs modules?

Upvotes: 0

Views: 519

Answers (1)

bgraham
bgraham

Reputation: 2027

It actually isn't because they are lazy loaded. A module only has access to the components which are defined in its declaration, or in the declarations of other modules it imports. So if you eagerly load your feature module into the AppModule, the feature module wont get access to the declarations of the AppModule.

There really isn't a way around this, its good design I think to be explicit about what a module has access to. One thing you can do though, if there is a common set of Material modules you want to import all over the place, is make a SharedMaterialModule:

@NgModule({
   import: [
      MatButtonModule,
      MatInputModule
   ],
   export: [
      MatButtonModule,
      MatInputModule
   ]
})
export class SharedMaterialModule {

}

You can then just import the SharedMaterialModule, and not have to import the MatButtonModule and any others that you want to have access to widely. Note though: if you add too much stuff here that isn't genuinely used everywhere, you can just end up making your feature modules have a bigger download footprint with stuff they aren't really using.

Upvotes: 1

Related Questions