Search code examples
angularangular-routerangular-module

Using another module in your module: imports vs. using loadChildren in routes


In my exploration of Angular, I've found two possible ways to use one module inside of another.

(Using the angular-express-starter project for reference)

  • Method 1: Declare it in the imports array. For example

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        SharedModule,
        FormsModule
      ]
    })
    
  • Method 2: Use loadChildrenin the routing. For example:

    export const routes: Route[] = [
      { path: '', pathMatch: 'full', redirectTo: 'weather'},
      { loadChildren: 'app/dashboard/dashboard.module#DashboardModule', path: 'dashboard' },
      { loadChildren: 'app/profile/profile.module#ProfileModule', path: 'profile' },
      { loadChildren: 'app/weather/weather.module#WeatherModule', path: 'weather' }
    ];
    

What are the practical differences between these two methods?


Solution

  • What are the practical differences between these two methods?

    The biggest difference is that modules loaded via loadChildren will have their own injector whereas providers from imported modules are merged into one root injector. It means that you can't inject providers from the lazy loaded module into other lazy loaded modules.

    Other differences:

    • you can't use loadChildren if you don't use routing
    • modules loaded via loadChildren will be loaded only when the corresponding route is navigated to

    For more information read