Dynamic Routing Using Angular 2

In this article, we will discuss the dynamic route concept in Angular 2.0. Before that, we first need to understand the requirement of routes in the AngularJS.

What is Routing?

Actually, Routing allows us to mention some aspects of the application's state in the URL. Using route concept in AngularJS, we can build our application for navigating different URLs or pages without changing the main URL of the application. Adding routing, however, allows the user to go straight into certain aspects of the application. This is very convenient as it can keep your application linkable and bookmarkable and allow users to share links with others.

Routing always allows us to,

  • Maintain the state of the web application
  • Implement modular applications so that we can navigate from one page to another page.
  • Implement the application based on the roles (certain roles have access to certain URLs)
If you want to get the details of basic routing concept in Angular 2.0 then you can check the below articles of Angular 2 Series,

Why the need for Routing?

Normally, when we create a multiple page application or website, we always need to navigate among various pages or Views. With ASP.NET, we can do that using the window.redirect method. But in AngularJS, we can do this using a Single Page Application. Single Page Applications are becoming very popular today due to phone/tablet apps. AngularJS helps to easily create the applications like that.

Why is Dynamic Routing Required?

We can create routing static code using route data as mentioned in the above articles. This process is OK if our web application contains a limited number of pages or components. But, it becomes difficult when we have a large number of HTML files with components and we need to populate the navigation URL details depending on the user-defined rule, perhaps, just like menus in a web application. In those cases, we need t configure the routeconfig dynamically by reading the data from an outer soure file (in other words, from a database or JSON file) when we can change or rearrange the data as required.

For implementing this, we need to provide menu details including component name and route key from dynamic source like database or JSON file. So that, whenever we need to insert the new menu or link in the UI, we just need to insert the data into that JSON files so that the menu is automatically populated at the run time.

For this, open Visual Studio 2015 and create a blank project file with Wesite Application Type Projects. Now, include the below code as mentioned below -

tsconfig.json
  1. {  
  2.   "compileOnSave": true,  
  3.   "compilerOptions": {  
  4.     "target": "es5",  
  5.     "module": "commonjs",  
  6.     "moduleResolution": "node",  
  7.     "sourceMap": true,  
  8.     "emitDecoratorMetadata": true,  
  9.     "experimentalDecorators": true,  
  10.     "removeComments": false,  
  11.     "noImplicitAny": false  
  12.   },  
  13.   "exclude": [  
  14.     "node_modules"  
  15.   ]  
  16. }  
systemjs.config.js 
  1. /**  
  2.  * System configuration for Angular samples  
  3.  * Adjust as necessary for your application needs.  
  4.  */  
  5. (function (global) {  
  6.     System.config({  
  7.         paths: {  
  8.             // paths serve as alias  
  9.             'npm:': 'node_modules/'  
  10.         },  
  11.         // map tells the System loader where to look for things  
  12.         map: {  
  13.             // our app is within the app folder  
  14.             'app': '.',  
  15.   
  16.             // angular bundles  
  17.             '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',  
  18.             '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',  
  19.             '@angular/core': 'npm:@angular/core/bundles/core.umd.js',  
  20.             '@angular/common': 'npm:@angular/common/bundles/common.umd.js',  
  21.             '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',  
  22.             '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',  
  23.             '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',  
  24.             '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',  
  25.             '@angular/http': 'npm:@angular/http/bundles/http.umd.js',  
  26.             '@angular/router': 'npm:@angular/router/bundles/router.umd.js',  
  27.             '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',  
  28.             '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',  
  29.             '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',  
  30.             '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',  
  31.   
  32.             // other libraries  
  33.             'rxjs': 'npm:rxjs',  
  34.             'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'  
  35.         },  
  36.         // packages tells the System loader how to load when no filename and/or no extension  
  37.         packages: {  
  38.             app: {  
  39.                 main: './main.js',  
  40.                 defaultExtension: 'js'  
  41.             },  
  42.             rxjs: {  
  43.                 defaultExtension: 'js'  
  44.             }  
  45.         }  
  46.     });  
  47. })(this);  
package.json 
  1. {  
  2.   "name": "Angular2_Sample",  
  3.   "version": "1.0.0",  
  4.   "scripts": {  
  5.     "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",  
  6.     "lite": "lite-server",  
  7.     "postinstall": "typings install",  
  8.     "tsc": "tsc",  
  9.     "tsc:w": "tsc -w",  
  10.     "typings": "typings"  
  11.   },  
  12.   "licenses": [  
  13.     {  
  14.       "type": "MIT",  
  15.       "url": "https://github.com/angular/angular.io/blob/master/LICENSE"  
  16.     }  
  17.   ],  
  18.   "dependencies": {  
  19.     "@angular/common": "~2.2.0",  
  20.     "@angular/compiler": "~2.2.0",  
  21.     "@angular/core": "~2.2.0",  
  22.     "@angular/forms": "~2.2.0",  
  23.     "@angular/http": "~2.2.0",  
  24.     "@angular/platform-browser": "~2.2.0",  
  25.     "@angular/platform-browser-dynamic": "~2.2.0",  
  26.     "@angular/router": "~3.1.0",  
  27.     "@angular/upgrade": "~2.2.0",  
  28.     "angular-in-memory-web-api": "~0.1.5",  
  29.     "bootstrap": "^3.3.7",  
  30.     "core-js": "^2.4.1",  
  31.     "reflect-metadata": "^0.1.8",  
  32.     "rxjs": "5.0.0-beta.12",  
  33.     "systemjs": "0.19.39",  
  34.     "zone.js": "^0.6.25"  
  35.   },  
  36.   "devDependencies": {  
  37.     "concurrently": "^3.0.0",  
  38.     "lite-server": "^2.2.2",  
  39.     "typescript": "^2.0.3",  
  40.     "typings": "^1.4.0"  
  41.   }  
  42. }  
app.dynamic.module.ts 
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { APP_BASE_HREF } from '@angular/common';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4. import { FormsModule } from "@angular/forms";  
  5. import { HttpModule } from '@angular/http';  
  6. import { RouterModule } from '@angular/router';  
  7.   
  8. import { routing, appRoutingProviders } from './route_config/dynamic/app.routes';  
  9. import { HomeComponent } from './route_config/dynamic/app.component.home';  
  10. import { HomePageComponent } from './route_config/dynamic/app.component.homepage';  
  11. import { MenuTreeComponent } from './route_config/dynamic/app.component.menu';  
  12.   
  13. import { HelloWorldComponent } from './samplecode/01_helloworld/helloworld.component';  
  14. import { FirstProgComponent } from './samplecode/01_helloworld/app.component.firstprog';  
  15. import { TemplateComponent } from './samplecode/01_helloworld/app.component.template';  
  16.   
  17. @NgModule({  
  18.     imports: [BrowserModule, FormsModule, HttpModule, routing],  
  19.     declarations: [HomePageComponent, HomeComponent, MenuTreeComponent, HelloWorldComponent, FirstProgComponent, TemplateComponent],  
  20.     bootstrap: [HomePageComponent],  
  21.     schemas: [NO_ERRORS_SCHEMA],  
  22.     providers: [appRoutingProviders],  
  23. })  
  24.   
  25. export class DynamicRouteModule { }  
index.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6.     <script src="resource/js/jquery.js"></script>  
  7.     <script type="text/javascript" charset="utf-8">  
  8.         function loadJson() {  
  9.             $(document).ready(function () {  
  10.                 $.getJSON('route_config/dynamic/data/route_menu.json', function (json) {  
  11.                     var data = [];  
  12.                     for (var i = 0; i < json.length; i++) {  
  13.                         if (json[i].isChildItem) {  
  14.                             for (j = 0; j < json[i].childItem.length; j++) {  
  15.                                 data.push({  
  16.                                     key: json[i].childItem[j].key,  
  17.                                     routeKey: '#' + json[i].childItem[j].routeKey,  
  18.                                     path: '#' + json[i].childItem[j].routeKey,  
  19.                                     component: json[i].childItem[j].componentName  
  20.                                 })  
  21.                             }  
  22.                         }  
  23.                     }  
  24.                     sessionStorage.setItem("routeData", JSON.stringify(data));  
  25.                     window.top.location.href = 'app.dynamic.module.html';  
  26.                 });  
  27.             });  
  28.         }  
  29.     </script>  
  30. </head>  
  31. <body onload="loadJson();">  
  32.     Angular 2 Home Page  
  33. </body>  
  34. </html>  
app.dynamic.module.html
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <!--<base href="/">-->  
  5.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6.     <meta charset="utf-8">  
  7.     <title>Angular 2 - Console</title>  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  9.     <meta name="description" content="">  
  10.     <meta name="keywords" content="">  
  11.     <meta name="author" content="">  
  12.   
  13.     <link href="resource/css/bootstrap.min.css" rel="stylesheet">  
  14.     <link rel="stylesheet" href="resource/css/font-awesome.min.css">  
  15.     <link rel="stylesheet" href="resource/css/jquery-ui.css">  
  16.     <link href="resource/css/style.css" rel="stylesheet">  
  17.     <link rel="shortcut icon" href="img/favicon/favicon.ico">  
  18. </head>  
  19. <body>      
  20.     <div class="content">  
  21.         <home-page></home-page>  
  22.     </div>  
  23.     <footer>  
  24.         <div class="container">  
  25.             <div class="row">  
  26.                 <div class="col-md-12">  
  27.                     <p class="copy">Copyright © 2017-2018 | <a href="http://www.c-sharpcorner.com/members/debasis-saha">Debasis Saha</a> </p>  
  28.                 </div>  
  29.             </div>  
  30.         </div>  
  31.     </footer>  
  32.     <script src="resource/js/jquery.js"></script>  
  33.     <script src="resource/js/bootstrap.min.js"></script>  
  34.     <script src="resource/js/jquery-ui.min.js"></script>  
  35.     <script src="resource/js/jquery.slimscroll.min.js"></script>  
  36.     <script src="resource/js/custom.js"></script>  
  37.   
  38.     <script src="node_modules/core-js/client/shim.min.js"></script>  
  39.     <script src="node_modules/zone.js/dist/zone.js"></script>  
  40.     <script src="node_modules/systemjs/dist/system.src.js"></script>  
  41.     <script src="systemjs.config.js"></script>  
  42.     <script>  
  43.         System.import('main.js').catch(function (err) { console.error(err); });  
  44.     </script>  
  45.   
  46.     <!-- Set the base href, demo only! In your app: <base href="/"> -->  
  47.     <script>document.write('<base href="' + document.location + '" />');</script>  
  48. </body>  
  49. </html>  
main.ts
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2. import { DynamicRouteModule } from './app.dynamic.module';  
  3.   
  4. platformBrowserDynamic().bootstrapModule(DynamicRouteModule);  
route_data.json
  1. [  
  2.   {  
  3.     "key": "item_01",  
  4.     "caption": "Basic Program",  
  5.     "displayOrder": 1,  
  6.     "isChildItem": true,  
  7.     "childItem": [  
  8.       {  
  9.         "key": "subitem_01",  
  10.         "caption": "Hello World",  
  11.         "displayOrder": 1,  
  12.         "componentName": "HelloWorldComponent",  
  13.         "routeKey": "/item_01_01"  
  14.       },  
  15.       {  
  16.         "key": "subitem_02",  
  17.         "caption": "First Program",  
  18.         "displayOrder": 2,  
  19.         "componentName": "FirstProgComponent",  
  20.         "routeKey": "/item_02_02"  
  21.       }  
  22.     ]  
  23.   },  
  24.   {  
  25.     "caption": "Nested Component",  
  26.     "displayOrder": 2,  
  27.     "isChildItem": false,  
  28.     "childItem": [  
  29.       {  
  30.         "caption": "Child Nested 1",  
  31.         "displayOrder": 1  
  32.       },  
  33.       {  
  34.         "caption": "Child Nested 2",  
  35.         "displayOrder": 2  
  36.       }  
  37.     ]  
  38.   },  
  39.   {  
  40.     "caption": "Data Binding",  
  41.     "displayOrder": 3,  
  42.     "isChildItem": false  
  43.   }  
  44. ]  
app.routes.ts
  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { HomeComponent } from './app.component.home';  
  3. import { HelloWorldComponent } from '../../samplecode/01_helloworld/helloworld.component';  
  4. import { FirstProgComponent } from '../../samplecode/01_helloworld/app.component.firstprog';  
  5. import { TemplateComponent } from '../../samplecode/01_helloworld/app.component.template';  
  6.   
  7.   
  8. export const routes: Routes = [  
  9.     { path: '', redirectTo: 'home', pathMatch: 'full' },  
  10.     { path: 'home', component: HomeComponent },  
  11.     { path: 'item_01_01', component: HelloWorldComponent },  
  12.     { path: 'item_02_02', component: FirstProgComponent },  
  13.     { path: 'template', component: TemplateComponent }  
  14.   
  15. ];  
  16.   
  17. export const appRoutingProviders: any[] = [  
  18.   
  19. ];  
  20.   
  21. export const routing = RouterModule.forRoot(routes);  
Now, we need to create some sample components like HomeComponet, HelloWorldComponent, FirstComponent, and Template Component which will be loaded by lazy loading concept in the run time.
 
Please find the attached screenshots.



For sample code, please find the attached project.

Up Next
    Ebook Download
    View all
    Learn
    View all