A Brief Introduction To Lazy Loading In Angular

Posted By : Damandeep Singh | 31-May-2018

Lazy Loading is a technique in Angular that is used to load components asynchronously when a specific route is activated. This can add some initial performance during the initial load, especially if you have two or more than two components with complex routing. It's anything but difficult to have highlights stacked just when client explores to their course out of the blue. this can be a huge help for performance and reduce bundle size.

Lazy loading can be done in two ways i.e 

  • Load children using main Route Configuration
  • Load children using feature Route Configuration

Load children using Main Route

Simply Give the path to the main Component you want to load followed by its children to specify its sub components.

{
        path:'user',
        component:UserComponent,
        children:[
            {
                path:'',
                redirectTo:'dashboard',
                pathMatch:'full'
            }
        ]
    }

Load Children using Feature Routing

Give the path to the main Component with loadChildren Attribute which specifies the module path with # and followed by the class name 

{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },

To use Loadchildren just add routerModule in feature module file 

and import RouterModule for Child Routing or Lazy Loading  

RouterModule is available in @angular/router;  package

now import it in @ngModule

imports: [RouterModule.forChild(routes)],

and create a new Module for lazy loading like (dashboard.module.ts)

and its routing like (dashboard.routing.ts) in this file give routing to those components which should be loaded lazily.

 

 

About Author

Author Image
Damandeep Singh

Damandeep Singh is a Front-end Developer having Good knowledge of HTML, CSS3/CSS, Bootstrap, Angular, Ionic. He likes to listen to Music in Free time.

Request for Proposal

Name is required

Comment is required

Sending message..