Monday, November 12, 2018

Lazy Loading module example

Let us see how Lazy loading is implemented using a simple example. Let us start with creating a new Angular application using the ng new command as follows.

ng new LazyLoadApp -app --routing


The -- routing switch adds routing to the new project. Now let us create another feature module which will be lazy loaded when the route is invoked in the root module, we can do this with the following ng command.

ng g m Feature –routing

Now we have to feature module, next let us create a component for this module using the following command.

ng generate component feature/myFeature

Next we will configure the routes so that we can see how Lazy loading works. To do this we have to link the Feature module with the root module’s route. This should be done in the root app’s routing module file app-routing.module.ts as follows.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
  {
    path: 'feature',
    loadChildren: './feature/feature.module#FeatureModule'
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Notice that we are using loadChildren in the routing configuration for LazyLoading. By default we will be component and we specify the component object for the route, but for lazy loading syntax we use loadChildren followed by a string that is the relative path to the module, a hash mark or #, and the module’s class name.

Now we have configured routing in the root module, we should also configure the routing of the feature module to load the default component when the route is invoked. Configuring route in the child/feature is required even though we don’t need routing since the module does not bootstrap on its own. If we don’t need routing in the child module we just configure the default route (‘’) so that the component gets loaded once we hit the route.

Let us open the routing file of the feature component feature-routing.module.ts and add the following.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MyFeatureComponent } from './my-feature/my-feature.component';

const routes: Routes = [
  {
    path: '',
    component: MyFeatureComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class FeatureRoutingModule { }

Now we are done with our Lazy Loading configuration, its time to build and run the sample. The output will be as follows.





Search Flipkart Products:
Flipkart.com

No comments: