By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules loads.
Lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
Configuring a lazy-loaded route
For lazy load Angular modules, use loadChildren (instead of component) in your AppRoutingModuleroutes configuration as follows.
const routes: Routes = [{ path: 'orders', loadChildren: () => import('./tailours/tailours.module').then(m => m.TailoursModule) }, { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }];
Step-by-step Guide
There are two main steps to setting up a lazy-loaded feature module:
Create the feature module with the CLI - using the --route flag.
Configure the routes.
You can setup your app with angular CMD - ng new customer-app --routing
After That create feature modules with the routing i.e. customers, tailours.
ng generate module customers --route customers --module app.module
ng generate module tailours --route orders --module app.module
In src/app/app-routing.module.ts File
add following routes
const routes: Routes = [{ path: 'orders', loadChildren: () => import('./tailours/tailours.module').then(m => m.TailoursModule) }, { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }]; In src/app/app.component.html File
add following code
<h1> {{title}} </h1><buttonrouterLink="/customers">Customers</button><buttonrouterLink="/orders">Orders</button><buttonrouterLink="">Home</button><router-outlet></router-outlet>
To see your app in the browser so far, enter the following command in the terminal window:
ng serve
Then go to localhost:4200 where you should see “customer-app” and three buttons.
Verify lazy loading
You can check to see that a module is indeed being lazy loaded with the Chrome developer tools. In Chrome, open the dev tools by pressing Cmd+Option+i on a Mac or Ctrl+Shift+j on a PC and go to the Network Tab.
Click on the Orders or Customers button. If you see a chunk appear, everything is wired up properly and the feature module is being lazy loaded. A chunk should appear for Orders and for Customers but will only appear once for each.
Comments