[Fixed] Why export MaterialModule

Issue

This StackBlitz demo,

app.module.ts export class MaterialModule {} and 2nd @NgModule does imports[ MaterialModule, ]. It doesn’t import {MaterialModule} at the top, so where does it get it from and why export it as a class? (rem-out both caused err)

Solution

  1. The purpose of MaterialModule is to re-export only the @angular/material modules which are used.
  2. MaterialModule is declared in the same file as the AppModule class – something which is not very common in real-world apps. The Angular style guide recommends having only one NgModule per file.
  3. MaterialModule is exported with export class MaterialModule {} because otherwise the Angular compiler will consider it private and won’t include it in the final build.

You can simplify the code by omitting the MaterialModule declaration and just include the used @angular/material modules in AppModule‘s imports:

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,

    // @angular/material modules
    MatButtonModule,
    MatCardModule,
    MatPaginatorModule
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: []
})
export class AppModule {}

Leave a Reply

(*) Required, Your email will not be published