Dynamic Routing in Angular 2 – Part 2

Posted by in Angular 2 category on for Beginner level | Points: 250 | Views : 805 red flag

This article is the part 2 continuation to previous article Routing in Angular 2.
Read Routing in Angular 2 :- Part 1 before this article.

This article is the part 2 continuation toprevious article Routing in Angular 2. This article will demonstrate overcome of the shortcoming of previous article. So the shortcoming is that if you see very closely in developer tool of browser under “Network” tab when the application is executed by loading MasterAngular.html page on the browser. Here you will see that even before we click on any of the link it will load all of the .JS files and other componentsat the start whether it is required or not, this is very bad part of the application. Let us consider if the application is having thousands of components and all of them are loading at the start which will make entire application slow and drastically affect overall performance.

Instead of loading all components right at the start we would like to load it as and when it isrequired or clicked on the link by the user. In other words at the start when “MainAngular.html” is open then only MasterPage component should load and when Customer link is clicked on “MainAngular.html” page then CustomerComponent should load finally loading “SupplierComponent” when Supplier link is clicked.

This is called as Lazy Loading or Lazy Routing and it is achieved with use of Dynamic Routing.

Till now loading of all components were done right at the start when “MainAngular.html”page was opened because we have only one Module named “MainModuleLibrary” in the project and under it all components are listed as shown in the image down below

If we create separate modules for each component with that we can get rid of the issue of loading all components at once. Next is to create two more separate modules, one for Customer and other for Supplier. Now in total we have three modules one is for Main Component, second for Supplier Component and third for Customer Component.

In our current project, we already have “MainModuleLibrary” created now we will create two more modules in it “SupplierModule” and other “CustomerModule”. And in each module we will keep only his component for referring purpose also it will be completely decoupled from each other.


As we have created two more new modules now we will edit “MainModuleLibrary” and keep only its relevant component i.e. “MasterPageComponent” in it deleting other two components. Also within @NgModule under declarations we will delete “CustomerComponent” and “SupplierComponent”.


Next go and edit “CustomerModule.ts” file as we have made copy of “MainModuleLibrary.ts” file and within that keep only “CustomerComponent” by deleting rest of the components present in it as shown in the image down below.

Also make the changes within @NgModule under declarations by deleting “MastePageComponent” and “SupplierComponent”.

Next is to change bootstrap text as “CustomerComponent” and finally export as “CustomerModule” as shown in the image down below.


And last but not the least make changes to SupplierModule.ts by deleting “MasterPageComponent” and “CustomerComponent” from top import.And within @NgModuledelete “MasterPageComponent” and “CustomerComponent” under declarations, change bootstrap to “SupplierComponent” and export it as “SupplierModule”.

Create Welcome Component

Create a new component called “WelcomeComponent” under Component folder which will be loaded when the application is executed on the browser. This component will be a simple component which will display simple message “Welcome to Customer-Supplier Management System” when browser loads the application. “WelcomeComponent” won’t point to any URL unlike other components. Followed to that corresponding html page will be loaded depending on the provided links clicked by the user.

But there are still some of the reference created earlier for static routing has to deleted and has to be rectified in order to work as Dynamic Routing or Lazy Loading. Remove existing references of Customer and Supplier component routing from “Routing.ts” available under Routing folder.

Routing Folder

In Explorer do the following: -

  1. Under Routing folder, first change existing “Routing” folder name to “MainRouting” folder.
  2. Now in the “MainRouting.ts” file delete all the existing CustomerComponent,
    SupplierComponent, MasterpageComponent.
  3. Import “WelcomeComponent”and correct path of that component.
  4. Change “ApplicationRoutes” name to “MainRoutes”for better readability.Please note
    that wherever in other components or modules or UI part we have mentioned name
    “ApplicationRoutes” should also be changed to “MainRoutes” to avoid error.
  5. Mention the component name “WelcomeComponent” to be loaded when application starts.
  6. When “MasterAngular.html” page is open then component name “WelcomeComponent” to be loaded.
  7. From the “import” we have removed all the components excluding “WelcomeComponent” and now there is a need to refer Customer and Supplier component but that we cannot do directly as it has already been removed from “import”. So to make things working here we have to use the term “loadchildren”. And with the help of “loadchildren” we can achieve what we wanted to do of “Dynamic routing” or lazy loading. “loadchildren” takes a simple string and with the help of that on the runtime it decided which modules or components to be loaded.
import {Component} from '@angular/core';

import  {WelcomeComponent} from "../Component/WelcomeComponent";

export const MainRoutes = [
    { path: '', component:WelcomeComponent }, 
    { path: 'UI/MasterAngular.html', component:WelcomeComponent }, 
    { path: 'Customer', loadchildren: 'Module/CustomerModule#CustomerModule' },
    { path: 'Supplier', loadchildren: 'Module/SupplierModule#SupplierModule' }


Now create two more routing files, one with name “CustomerRouting.ts” and other with name “SupplierRouting.ts”. Under “CustomerRouting.ts” just import “CustomerComponent” and add its corresponding location path for file location in the project folder. And for exposing it outside use “export” it as CustomerRoutes with child route path as “Add” which loads “CustomerComponent”.

Similarly we will create second file of “SupplierRouting.ts” and export it as SupplierRoutes with child route path as “Add” and loading “SupplierComponent”.

import {Component} from '@angular/core';
import {SupplierComponent} from '../Component/SupplierComponent';

export const SupplierRoutes = [
    { path: 'Add', component: SupplierComponent }

Once we are finished with configuring “MainRouting.ts” and creation of two more “SupplierRouting.ts” and “CustomerRouting.ts” next we will add child route to routerlink.

UI folder > MasterPage.html

Next change we have to do in “MasterPage.html” under UI folder. In “MasterPage.html” add child route as “Add” to existing “routerlink” so now complete path for “Supplier” link would be Supplier/Add where now “Supplier” is Main route and “Add” becomes child route.

<a [routerLink]="['Supplier/Add']">Supplier</a>

And for “Customer” link, here after Customer add text “Add” in “routerlink” to make “Customer” is Main route and “Add” becomes child route

<a [routerLink]="['Customer/Add']">Customer</a> 


Once you are finished with doing the changes in MasterAngular.html page next is to go and do the changes in “MainModuleLibrary.ts” file available under Module folder. Below are changes done written down in simple steps: -

  1. On the top under “import” change path of “Routing” to “MainRouting” as earlier we have changed name of “Routing.ts” to “MainRouting.ts”.
  2. Change “ApplicationRoutes” to “MainRoutes” as in the “MainRouting.ts” we have changed export name.
  3. Import new component with name “WelcomeComponent” created and give the complete path.
  4. Now under @NgModule and within its “imports”change RouterModule name from existing “ApplicationRoutes” to “MainRoutes”.
  5. Next under “declarations” of @NgModule add “WelcomeComponent”.


Next is to make changes under “CustomerModule.ts” file. Below are the steps for the same: -

  1. Under “import” change path from “Routing” to “CustomerRouting”.
  2. Change name from “ApplicationRoutes” to “CustomerRoutes”.
  3. Under imports of @NgModule change RouterModule from “ApplicationRoutes” to “CustomerRoutes”.
  4. Change “RouterModule.forRoot” to “RouterModule.forChild”. Here we have made this change in order to achieve lazy loading or dynamic routing.


Similarly make the changes to “SupplierModule” as we did changes to “CustomerModule” as mentioned in the below steps: -

  1. Under “import” change path from “Routing” to “SupplierRouting”.
  2. Change name from “ApplicationRoutes” to “SupplierRoutes”.
  3. Under imports of @NgModule change RouterModule from “ApplicationRoutes” to “SupplierRoutes”.
  4. Next to achieve lazy loading change “RouterModule.forRoot” to “RouterModule.forChild”.

Please Note: In NgModule of both “CustomerModule” and “SupplierModule” Browser Module should not be present only it should be present in one location under “MainModuleLibrary” only.

After we have changed and configured all our Routing, Module and Component within the project as per achieving goal of dynamic loading. Next is to execute application and for that run http-server.

Run http-server

To run the server, we have to open “Integrated Terminal” available under “View”option of Menu bar. Once “Integrated Terminal” is open at the bottom go to the project folder location in case if the project location is not open.

Now to run the server type “http-server” as command on the “Integrated Terminal” command prompt as shown in the image down below.


With this command http server will start and next it will show the address path and port on which server is running: -

Now copy this path and port on which http server is running and paste it on the address bar of the chrome browser.

Execute Application

Then moment you paste address path and port no. on the browser and press enter on keyboard, application will start displaying all the folder and files of the project.

Now in order to run our project we first open “MasterAngular.html” page which is available under UI folder.

Open UI folder

From all the folders displayed on the browser click on UI folder link

After you click on UI folder link it will show you inner details of the folder which contains all the html pages under it you will find “MasterAngular.html” page.

Open MasterAngular.html

UnderUI folder which is open, click on “MasterAngular.html” in order to start the application.

Once “MasterAngular.html”page is open then it will load Welcome Component as the default. This has become possible because we have set it under “MainRouting.ts” to open Welcome Component.

Supplier Component loads

Now on the application if you see under it has Left Menu with links on it, on “Supplier” link is clicked it will open supplier page within the dynamic area which is and under it loads with the supplier page. On the top within address bar of the browser if you see now there is a link composed of “Supplier” as main route and “Add” as child route displayed followed by server path and port.

After clicking on “Supplier” link, supplier page and supplier link is loading correct also we need to check whether supplier component is loaded or not. In order to check the same press F12 on the keyboard in order to open developer tool. Once tool is open click on “Network”under it click “All” and on search box type “component”. If you see in the image down below SupplierComponent is loaded successfully.

Customer Component loaded

Similarly we will click “Customer” link under Left Menu and check whether “CustomerComponent” is loading successfully. When “Customer” link is clicked it will load Customer.html page within the dynamic area and simultaneously link on the address bar of the browser will change from “Supplier/Add” to “Customer/Add” and under developer tool under “Network” if you see now “CustomerComponent” is loaded successfully.

So with dynamic loading it is clear that not all components loads at the beginning when application starts instead it loads only that component when it is required or requested by the user.

Also suggesting you to go to the following link of step by step Angular 2 project video based series which will help you to learn it practically: -

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Posted by: Endylong on: 4/17/2017 | Points: 25
Thank you very much for a very useful article.

Login to post response

Comment using Facebook(Author doesn't get notification)