#Angular5 #LazyLoading - how to lazy load a component?

To lazy load a module on a different url path, you can follow the following steps using Angular CLI:
You can check how to verify lazy-loading at the bottom.

Angular CLI
Angular CLI homepage

Lazy Loading steps

1) Create a new project using routing flag

ng new popcorn --routing

2) Create a module

ng generate module modules/movie 
ng g m modules/movie 

3) Create a component inside the module

ng generate component ./modules/movies/movies --module ./modules/movies/movies.module.ts
ng g c ./modules/movies/components/movies --module ./modules/movies/movies.module.ts

4) Update your app-routing.module.ts to be so.
The routes variable means there is a path 'movies'. When the url points to movies, it will load movies module.

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

const routes: Routes = [
    path: 'movies',
    loadChildren: './modules/movies/movies.module#MoviesModule'

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

5) Update your lazy loading module to be so.
When this module is loaded, it will launch MoviesComponent which is my lazy loading component.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MoviesComponent } from './movies.component';

const routes: Routes = [
    path: '',
    component: MoviesComponent

  imports: [
  providers: [],
  declarations: [

export class MoviesModule {}

If you want to have more paths to the component, you can modify path in the routes variable.
const routes: Routes = [
    path: ‘recent',
    component: RecentMoviesComponent

6) Use routerLink to set up a link to your lazy loading module in your app.component.html

  <button><a routerLink="/movies"><h1>Movies</h1></a></button>


1) Run your app on local host by using ng serve. 
2) Open up your browser inspector / developer tools. On chrome, the shortcut keys to open it is cmd + alt + j
3) You can then switch over to network tab (cmd + 6 if you have the shortcut key turned on) 
4) Click on the button to load your lazy loading module. 
5) You will notice that its module file is separated from the other source files and only sent when triggered. 

Thanks for reading!