DEV Community

Nitin Jadhav
Nitin Jadhav

Posted on

2 2

[Done Quick] Easy Lazy loading with Angular 8

Here are the steps to quickly add lazy loaded modules (loads only after the user navigates to a specific feature or page):

Note that your app must be arranged as feature modules instead of one big AppModule. Make sure that you have installed latest angular cli with the command npm install -g @angular/cli.

step 1: create a Demo App

ng new MyApp --routing

step 2: Add a feature module and component inside the new module which needs to be lazily loaded

ng g module feature --routing
ng g component MyFeature --module=feature

step 3: In your app.component.html add a link to the lazy module

<a routerLink="/feature">Lazy feature</a>
note that this file also has <router-outlet></router-outlet>

step 4: Add Lazy loading to the main app router file (app-routing.module.ts). Notice the import statement - this is where the magic happens!

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

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

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

step 5: Finally, add lazy routing to feature module routing file (feature-routing.module.ts)

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 { }

That's it! Run the project with ng serve and click the link in your new app. See the browser console for the lazy loaded module.

Devtools show lazy angular module loading

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay