Search code examples
angularangular-materialangular8angular-material-7

Angular 8 - Is importing all material modules into the main app module better than importing individual material modules inside different modules?


What is the best way to import material modules into an Angular 8 project? Is it by importing the material.module.ts to app main module and then use it in other modules:

import { NgModule } from '@angular/core';

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

Or simply import the mainly used modules of material in each module?

Per example, if I only used mat-card in ProductsModule, I simply import MatCardModule in the products module and be done with it.


Solution

  • It completely depends on your where all the Components exposed by Angular Material would be used inside the App.

    If only some components in some modules use components exposed by Angular Material, it would make sense to import these modules in the modules that those components are a part of.

    Eg: Let's for arguments' sake say that your App has three modules: CartModule, CheckoutModule, ProfileModule. And only your CartModule uses one of the Angular Material Components. Also if this CartModule is Lazily Loaded. In this case, it would make a lot of sense to just import that particular Angular Material Module in the CartModule.


    This, however, won't be the case in most of the scenarios.

    In most of the cases and being mindful of a consistent look and feel, we generally tend to use a lot of Components exposed by Angular Material modules throughout the App. So in that case, to make it more uniform and manageable, we generally create an AppMaterialModule the way you've done in the question itself. And then we import this module in the modules where we want to use these components in. And if we are to use these components throughout different modules across the application, we generally import the AppMaterialModule in the SharedModule and export it from there. That way, the components that we've exposed as a part of the AppMaterialModule would be accessible throughout the App.

    Hope this clears your doubts.