Monday, November 12, 2018

Lazy loading modules in Angular


Lazy loading refers to loading modules with a delay, it is suitable for medium to larger applications where the number of dependent modules are more and loading all of them during the initial load is not feasible. In lazy loading each route is mapped to a module, but the module is not loaded till the route is invoked. Initial loading of the application will be quick since only the root module gets loaded when the application loads in the browser.

To implement Lazy Loading we need a root module and a one or more feature modules. In the routing configuration of the route module we map each route to one of the feature modules, when the route is invoked the corresponding feature module is loaded dynamically and rendered in the browser.

To configure lazy loading the routing configuration should be slightly different from how we configure eager loading. In eager loading we import all the dependent components into the main module and map the components to different routes in the module routing. When a specific route is invoked the corresponding component is loaded in the root component.

const appRoutes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent }
];


To configure lazy loading we will not import the child module/component into the root module instead we will specify a string which gives the path of the Feature module and the module class name.

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: './feature/feature.module#FeatureModule'
  },

Also in the feature module we configure the default route to load the bootstrap component when the route is invoked.


Search Flipkart Products:
Flipkart.com

No comments: