Routing In Angular 4

Introduction

Angular framework is mainly focused and good for the SPA (Single Page Architecture). It loads a single full HTML page and dynamically loads or updates the partial pages as per user request. And, that is achieved with the help of router. A set of partial page loading rule and urls is defined in router to render or load partial pages based on user request.    

 
I will explain the detailed concept of router in Angular 4.

Inside pakage.json

package.json is a file required to define all dependencies, build rule, build path, start up of server and application, etc. so, you are required to define the below dependencies for the Angular 4 router:
  1. "@angular/router""~4.0.0",  
Under "dependencies" category, like below.
  1. "author""",  
  2.   "license""MIT",  
  3.   "dependencies": {  
  4.     "@angular/common""~4.0.0",  
  5.     "@angular/compiler""~4.0.0",  
  6.     "@angular/core""~4.0.0",  
  7.     "@angular/forms""~4.0.0",  
  8.     "@angular/http""~4.0.0",  
  9.     "@angular/platform-browser""~4.0.0",  
  10.     "@angular/platform-browser-dynamic""~4.0.0",  
  11.     "@angular/router""~4.0.0",  
  12.   
  13.     "angular-in-memory-web-api""~0.3.0",  
  14.     "systemjs""0.19.40",  
  15.     "core-js""^2.4.1",  
  16.     "rxjs""5.0.1",  
  17.     "zone.js""^0.8.4"  
  18.   },  
Inside systemjs.config.js

Router should be defined inside "map" of systemjs.config.js like below.
  1. map: {  
  2.      // our app is within the app folder  
  3.      'app''app',  
  4.   
  5.      // angular bundles  
  6.      '@angular/core''npm:@angular/core/bundles/core.umd.js',  
  7.      '@angular/common''npm:@angular/common/bundles/common.umd.js',  
  8.      '@angular/compiler''npm:@angular/compiler/bundles/compiler.umd.js',  
  9.      '@angular/platform-browser''npm:@angular/platform-browser/bundles/platform-browser.umd.js',  
  10.      '@angular/platform-browser-dynamic''npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',  
  11.      '@angular/http''npm:@angular/http/bundles/http.umd.js',  
  12.      '@angular/router''npm:@angular/router/bundles/router.umd.js',  
  13.      '@angular/forms''npm:@angular/forms/bundles/forms.umd.js',  
  14.   
  15.      // other libraries  
  16.      'rxjs':                      'npm:rxjs',  
  17.      'angular-in-memory-web-api''npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'  
  18.    },  
Inside app folder

All folders, modules, and components remain inside the app folder. So, one main router file will be inside the app root folder where the other sub components' router details like routing path, strategy, etc. will be defined.
 
File name: app.routes.ts
  1. import { ModuleWithProviders }  from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3.   
  4. import { dogRoutes }    from './dogs/dog.routes';  
  5. import { catRoutes }    from './cats/cat.routes';  
  6. import {birdRoutes} from './birds/bird.routes';  
  7.   
  8. // Route Configuration  
  9. export const routes: Routes = [  
  10.   {  
  11.     path: '',  
  12.     redirectTo: '/dogs',  
  13.     pathMatch: 'full'  
  14.   },  
  15.   ...catRoutes,  
  16.   ...dogRoutes,  
  17.   ...birdRoutes  
  18. ];  
  19.   
  20. export const routing: ModuleWithProviders = RouterModule.forRoot(routes);   
This app.routes.ts file will be imported inside app.module.ts file like below.
  1. import { NgModule }       from '@angular/core';  
  2. import { BrowserModule }  from '@angular/platform-browser';  
  3. import { FormsModule }    from '@angular/forms';  
  4. import { HttpModule, JsonpModule } from '@angular/http';  
  5.   
  6. import { AppComponent } from './app.component';  
  7. import { DogListComponent } from './dogs/dog-list.component';  
  8. import {CatListComponent} from './cats/cat-list.component'  
  9. import {BirdListComponent} from './birds/bird-list.component';  
  10.   
  11. import { routing } from './app.routes';  
  12. import {MyFilterPipe} from './filter/MyFilterPipe';  
  13.   
  14. @NgModule({  
  15.   imports: [  
  16.     BrowserModule,  
  17.     FormsModule,  
  18.     HttpModule,  
  19.     JsonpModule,  
  20.     routing  
  21.   ],  
  22.   declarations: [  
  23.     AppComponent,  
  24.     DogListComponent,  
  25.     CatListComponent,  
  26.     BirdListComponent,  
  27.     MyFilterPipe  
  28.   ],  
  29.   bootstrap: [ AppComponent ]  
  30. })  
  31. export class AppModule {  
  32. }  
And, main routing strategy will be defined inside app.component.ts file.
  1. import { Component } from '@angular/core';  
  2.   
  3.   
  4. @Component({  
  5.   selector: 'my-app',  
  6.   template: `  
  7.    <div>  
  8.      <nav>  
  9.      <a class="mdl-navigation__link" [routerLink]="['/']">Home</a>  
  10.      <a class="mdl-navigation__link" [routerLink]="['/cats']">Cats</a>  
  11.      <a class="mdl-navigation__link" [routerLink]="['/dogs']">Dogs</a>  
  12.      <a class="mdl-navigation__link" [routerLink]="['/birds']">Birds</a>  
  13.     </nav>  
  14.     </div>  
  15.     <div>  
  16.       <router-outlet></router-outlet>  
  17.     </div>  
  18.   `,  
  19. })  
  20.   
  21. // App Component class  
  22. export class AppComponent{}  
Important point
 
Don't use the below line for the router as this is now deprecated.
  1. import { provideRouter, RouterConfig } from '@angular/router';  
The following lines have been introduced in place of the above deprecated line.
  1. import { ModuleWithProviders }  from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
Don't use provider like below as it is deprecated now.
  1. export const APP_ROUTER_PROVIDERS = [  
  2.   provideRouter(routes)  
  3. ];  
Below line has been introduced in place of the above line.
  1. export const routing: ModuleWithProviders = RouterModule.forRoot(routes);  
Sub-router

I have defined three sub-routes named cateRoutes, birdRoutes, and dogRoutes in the above main router "app.router.ts". So, sub routers should be defined like below,
  1. import { Routes } from '@angular/router';  
  2.   
  3. import { BirdListComponent } from './bird-list.component';  
  4.   
  5. export const birdRoutes: Routes = [  
  6.   { path: 'birds', component: BirdListComponent }  
  7. ];  
This router will import the corresponding component and define the path named "birds" to load its partial page defines inside the component like below,
  1. import { Component } from '@angular/core';  
  2. import {Birds} from '../models/birds';  
  3.   
  4. @Component({  
  5.   template: `  
  6.     <strong>Birds</strong>  
  7.     <p>List of Birds</p>  
  8.     <div>  
  9.       <ul>  
  10.        <li *ngFor="let bird of birds">  
  11.          {{bird.id}} {{bird.name}}  
  12.        </li>   
  13.       </ul>  
  14.     </div>  
  15.     `  
  16. })  
  17.   
  18. export class BirdListComponent {  
  19.   birds: Birds[] = [  
  20.   {id: 11, name: 'Mr. Nice'},  
  21.   {id: 12, name: 'Narco'},  
  22.   {id: 13, name: 'Bombasto'},  
  23.   {id: 14, name: 'Celeritas'},  
  24.   {id: 15, name: 'Magneta'},  
  25.   {id: 16, name: 'RubberMan'},  
  26.   {id: 17, name: 'Dynama'},  
  27.   {id: 18, name: 'Dr IQ'},  
  28.   {id: 19, name: 'Magma'},  
  29.   {id: 20, name: 'Tornado'}  
  30.   ]  
  31. }  
You can download and check other component's router details in more details from the attached code.
 
Steps to execute project
 
Node.js must be installed into your computer.

Download and unzip the code ~~ go to root folder "routingpractice" ~~ Open command prompt ~~ type "npm start"~~ It will start the server and execute the website on brower. 
 
Output


Conclusion

Routes and RouterModule are the important part of Angular 4's router. It is very easy and robust. It provides flexibility to create sub-router and call into one main router for the different components.

Up Next
    Ebook Download
    View all
    Learn
    View all