Implementing Lazy Loading in Angular 6

0
3088
views

At some point of time in your application you do feel like the size of the application is growing and starts having doubt about application performance.

Initially at one go you don’t want load all the components. You will only want to load the components that are needed when the application starts running. As the user navigates through the routes load those components required for that particular route. This will helps us to achieve good performance and easy to work around with components.

To achieve this we need to created separate modules and register the components to those modules separately. (It is like grouping similar things).

Let’s talk Code

Let’s say we have two modules home(home.module.ts) and dashboard(dashboard.modules.ts). We will register the components needed for home in home.module.ts and we will register components needed for dashboard in dashboard.module.ts

├── home.module.ts
│ └── login.registration.ts
│ └── register.component.ts
│ └── home.component.ts
├── dashboard.module.ts
| └── profile.component.ts
│ └── settings.component.ts

First of all you need to create these modules in your application and generate the components in each of these modules.

We will create separate our main app.routing.ts file


import { Routes, RouterModule } from '@angular/router';

const MAINMENU_ROUTES: Routes = [

    {path: '...',
    loadChildren: 'app/home/home.module#HomeModule'},

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

];
export const CONST_ROUTING = RouterModule.forRoot(MAINMENU_ROUTES, {onSameUrlNavigation: 'reload'});

Don’t forget to register this app.routing.ts file in our main app.module.ts file and mention the CONST_ROUTING in imports also.

This app.routing.ts file will now help us to lazy load the components whenever we navigate to dashboard and home(only those components will be loaded to the route which you navigate).

By now your application structure should look like this

├── app
│ └──Home
├── home.module.ts
│ └── login.registration.ts
│ └── register.component.ts
│ └── home.component.ts
│ └──Dashboard
├── dashboard.module.ts
| └── profile.component.ts
│ └── settings.component.ts
│ └── app.routing.ts

Implementing Lazy Loading in Angular 6

Now lets go into the home.module.ts file

import { Registration } from './registration/registration.component';
import { LoginService } from './login.service';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { MaterialModule } from '../material.module';
import { FormsModule,ReactiveFormsModule,FormControlDirective, FormGroupDirective } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';
import { LoginComponent } from './login/login.component';


const routes: Routes = [
   

    {
        path: 'home',
        component: HomeComponent
    },

    { path: '', redirectTo: 'home', pathMatch: 'full' },

    {
        path: 'Login',
        component: LoginComponent
    },
    
    {
        path: 'registration',
        component: RegistrationComponent
    }
  ];


@NgModule({
    declarations: [
        RegistrationComponent,
        LoginComponent,
        HomeComponent
    ],

    imports: [
        CommonModule,
        RouterModule.forChild(routes),
        MaterialModule,
        FormsModule,
        ReactiveFormsModule,
        BrowserAnimationsModule,
        HttpModule,
       
    ],
    exports: [
        RouterModule,
    ],
   
    providers: [LoginService],

})
export class HomeModule { }

Notice that in import we did that RouterModule.forChild(routes) rather than .forRoot().

Implementing Lazy Loading in Angular 6

Now lets take a look into the dashboard.module.ts

import { Profile } from './profile/profile.component';
import { ApiService } from './api.service';
import { SomeGuard } from './some.guard';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { Settings } from './settings/settings.component';
import { MaterialModule } from '../material.module';
import { FormsModule,ReactiveFormsModule,FormControlDirective, FormGroupDirective } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';


const dashboard_Routes: Routes = [

      {
        path: 'settings',
        component: SettingsComponent,
        children:[
        
          {
            path: 'editaccount',
            component: EditaccountComponent,
            resolve: {
              jwtDetails: SomeGuard
            },
            data: { 
                expectedRoute: ['editaccount']
              } 
          },
          {
            path: 'feedback',
            component: FeedbackComponent,
            resolve: {
              jwtDetails: SomeGuard
            },
            data: { 
                expectedRoute: ['feedback']
              } 
          },

          
        ],
            path: 'profile',
            component: ProfileComponent,
            resolve: {
              jwtDetails: SomeGuard
            },
            data: { 
                expectedRoute: ['profile']
              } 
          },
      },
  
];


@NgModule({
    declarations: [
        ProfileComponent,
        SettingsComponent,
 
    ],

    imports: [
        CommonModule,
        RouterModule.forChild(dashboard_Routes),
        MaterialModule,
        FormsModule,
        ReactiveFormsModule,
        BrowserAnimationsModule,
        HttpModule,
       
    ],
    exports: [
        RouterModule,
    ],
   
    providers: [ApiService],

})
export class DashboardModule { }

As you can see in the Dashboard There are two main routes Profile and Setting for the Settings there are secondary routes.

By default Home module will be loaded if login and navigate to the dashboard Dashboard module related components will be loaded.

We now have successfully achieved lazy loading concept in our application.

Happy Coding..!