Search code examples
angularangular-materialangular7angular-module

Angular material theme not applied in child module after creating Material Module and importing it into app.module


As suggested in many other tutorials, I've decided to declutter my app.module from specific angular material modules and have created a separate module called 'material module' -- then I have imported this module directly into the app.module's imports array.

Now if I have a material button in app.component.html all is good and themeing is applied.

However, I have an Auth Module which is being displayed via the and any angular themeing does not get applied in that module, they're all basic html elements.

I'm sure I'm missing something really obvious about how modules are supposed to work in angular but after reading a lot of threads here and some forums via google search + documentation, I can't figure out what it is that I'm missing.


Solution

  • The problem here is not with the theme but the AuthModule not knowing how to resolve the material components.

    In Angular a module acts as compilation context, if you don't import the MaterialModule into the AuthModule then the material components are outside of the context and angular doesnt know anything about them.

    Importing your MaterialModule into your AuthModule will resolve this issue, for example:

    material.module.ts:

    @NgModule({
      imports: [MatButtonModule, MatListModule],
      exports: [MatButtonModule, MatListModule],
    })
    export class MaterialModule {}
    

    auth.module.ts

    @NgModule({
      imports: [CommonModule, MaterialModule],
      providers: ...,
    })
    export class AuthModule {}
    

    Note that

    • MaterialModule exports MatButtonModule
    • AuthModule imports MaterialModule Therefore, AuthModule has access to the Components defined in MatButtonModule

    For more information on this see the angular docs https://angular.io/guide/sharing-ngmodules