What is Lazy Loading in Angular

What is Lazy Loading in Angular:-

Lazy loading is a useful concept in angular. because it is on-demand work. it is a process of loading NgModules only when you navigate to the route. If you have a lot of application with numerous routes, you should consider using this concept it will keep the initial bundle size is smaller and as a result, the application can be loaded much faster.


How to Create Lazyloading Module with Routing:-

Next, we need to create our feature with the component to navigate to.
So we create a new module, execute the following command.


ng generate module admin --route admin --module app.module

so open your terminal and the command is Run.

you can see a new module called admin and the route path to load the home component. In addition, it will add the homepage route inside the Routes array inside this module as the --module options.



app-routing.module.ts

Here is the result of app-routing.module.ts file.

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

const routes: Routes = [
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) },
];

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


The loadChildren property is used to specify the module that needs to be lazy-loaded when it is first navigated to.
we need to create 2 more modules called profile and settings.
So let’s create.


ng generate module profile--route profile --module app.module
ng generate module settings --route settings--module app.module

nav.component.html

We will create a list of mat-list and routerlink in nav.component.html

<mat-nav-list>
<a mat-list-item routerLink="/settings">Settings</a>
<a mat-list-item routerLink="/admin">Admin</a>
<a mat-list-item routerLink="/profiles">Profiles</a>
</mat-nav-list>



                                                            Thank You

Previous
Next Post »

1 comments:

Click here for comments
Unknown
admin
June 6, 2020 at 5:52 AM ×

nice post

Congrats bro Unknown you got PERTAMAX...! hehehehe...
Reply
avatar