How to use loadChildren - Lazyloading in Angular
Lazy loading in Angular
- Lazy loading modules in Angular allows you to load modules when it is actually necessary.
- Lazy loading will help you to achieve performance.
- Lazy loading will help you to decrease the size.
- By using loadChildren(), we can implement Lazy loading in Angular
Let's take an example to understand it
- Create a project, which will load different components from a different module.
We will follow below method to implement lazy loading
- Step 1 : Create a new project using command ng new project-name
- Step 2 : Create 3 different module to implement lazy loading
-
Step 3 : Open app\app-routing.module.ts and place below code
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'college', loadChildren: () =&; import('./college/college.module').then(college =>; // tslint:disable-next-line: no-unused-expression college.CollegeModule ) }, { path: 'student', loadChildren: () =>; import('./student/student.module').then(student =>; // tslint:disable-next-line: no-unused-expression student.StudentModule ) }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } loadChildren -> This is lazy loading 😊
-
Step 4: Open app.module.ts and place and replace import with below code
imports: [ BrowserModule, AppRoutingModule, CollegeModule, StudentModule ], - Step 5: open app.component.html and place below code
- Step 6: hit ng serve command. it will start working
awesome info
ReplyDelete