There are three steps to set up a lazy loading feature in Angular.
- Create a feature module.
- Create the routing module for the feature module.
- The configuration of the routes.
Prerequisites:
You should have an Angular app. If you do not have then run the following command.
This command will create a ‘lazy-loading-app’ and –routing flag generate a file ‘app-routing.module.ts’. Now move into your project directory i.e lazy-loading-app
ng new lazy-loading-app --routing
Step 1 and 2: Create a feature module and routing module.
Run the following command.
ng generate module books --routing
This command will create a books folder with two files ‘BooksModule’ and ‘BooksRoutingModule’
Now add a component to the feature module books.
Run the following command to generate the component.
“ng generate component books/book-list”
This will generate a folder inside the books called book-list with all the required file which make the component.
Add the following code to your app.component.html file which is present inside the src/app
<h2>This is lazy loading example</h2>
<button routerLink="/books/book">Load Books</button>
<router-outlet></router-outlet>
Step 3. Configure the routes
In ‘src/app/app-routing.module.ts’ update the routes array from the following code.
const routes: Routes = [
{
path: 'books',
loadChildren: 'app/books/books.module#BooksModule'
}
];
Now configure the feature module’s routes
Add the following code into the “src/app/books/books-routing.module.ts”
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BookListComponent } from './book-list/book-list.component';
const routes: Routes = [
{
path: '',
component: BookListComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class BooksRoutingModule { }
Now run the following command to confirm its working.
ng serve --open
This command will open a browser at port 4200.
Now open your network tab and then click on ‘Load Books’ button.
If a chunk appears, You have done everything correctly.