Search code examples
angularangular-materialangular-routingangular-module

Angular Material available only when imported via Shared Module in Router Module


Following the Angular guidelines, I am trying to create a sample project which consists of several feature modules.

In order to use Angular Material in each of the modules, I have created a shared module which imports and exports these material modules. This Shared Module is imported wherever Angular Material is required.

According to the guidelines, each of the feature module should have it's own Router Module and thus I have created one for each feature.

I want to keep just the routing related items in the Routing Module thus imported the Shared Module in the Feature Module and to my surprise it did not work i.e. Material directives were not working.

//Feature Module
@NgModule({
    imports: [..., SharedModule], //SharedModule import doesn't make material available
    declarations: []
})

Once I imported this Shared Module in Router Module, the Material components started to work.

//Feature Router Module
@NgModule({
    imports: [..., SharedModule], //SharedModule makes material available
    declarations: []
})

How can I make it work by importing the Shared Module in the Feature Module?

Demo at: https://stackblitz.com/edit/angular-segregated-modules?embed=1&file=src/app/Modules/Sub/sub.module.ts


Solution

  • Looking at the StackBlitz you linked, SubComponent is declared in SubRoutesModule. The component will only have access to the imports of the module it's declared in, which explains the problem you describe.

    How can I make it work by importing the Shared Module in the Feature Module?

    Remove SubComponent from the declarations in SubRoutesModule and add it to the declarations in SubModule.