Navigation In Angular Between Different Routes

Introduction

Router is an important concept and part of Angular 4 for the navigation between different component's View. It loads the different components, or in AngularJS concept, you can say different partial pages based on the requested router. It is also useful to pass the data from one component to different components. AngularJS has also the same type of concept with the use of $state.go() for navigation and transfer of the data.

Router Navigate

It is used to navigate and pass the data from one component to another component. It is required to import like below for the use of router.
  1. import { Router } from '@angular/router';  
It should be passed in component's constructor like below.
  1. constructor(private nutanixervice: NutanixService, private router:Router) {  
  2.     this.curPage = 1;  
  3.     this.pageSize = 10;  
  4.   }  
Let's develop step by step.
 
Create a folder project structure for your learning project, like below.
 
 
 
Here, some .js files are auto-generated JavaScript files. You need to concentrate on .ts files. In the above root structure, I have created two separate components - home and details. I will explain the navigation between these two components.
 
Component "home" 
 
Create three different files one by one like below,
 
home-list.component.ts
 
All home related logics are defined into this component.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { NutanixService } from '../dataservices/nutanix.service';  
  3. import { Observable } from 'rxjs/Observable';  
  4. import { Router } from '@angular/router';  
  5.   
  6. @Component({  
  7. templateUrl: './app/home/home.html'  
  8. })  
  9.   
  10. export class HomeListComponent implements OnInit{  
  11.   nutaNixGitHubData: any;  
  12.   curPage : number;  
  13.   pageSize : number;  
  14.   private selectedObj : any;  
  15.   private ValueId : number = 1;  
  16.   private selectedName: 'java';  
  17.   
  18.   technologies = [  
  19.   { id: 1, name: "java" },  
  20.   { id: 2, name: "python" },  
  21.   { id: 3, name: "javaScript" },  
  22.   { id: 4, name: "php" },  
  23.   { id: 5, name: "ruby" }  
  24. ];  
  25.   
  26.   constructor(private nutanixervice: NutanixService, private router:Router) {  
  27.     this.curPage = 1;  
  28.     this.pageSize = 10;  
  29.   }  
  30.   
  31.   ngOnInit() {  
  32.    this.getNutanixRepo();  
  33.   }  
  34.   
  35.   currentPageClick() {  
  36.     this.curPage = this.curPage+1;  
  37.      this.getNutanixRepo();  
  38.   }  
  39.   
  40.   prevPageClick() {  
  41.     this.curPage = this.curPage-1;  
  42.      this.getNutanixRepo();  
  43.   }  
  44.   
  45.   getNutanixRepo() {  
  46.      this.nutanixervice.getNutanixGitHubData(this.selectedName, String(this.curPage)).subscribe(  
  47.       (data)=>{  
  48.         this.nutaNixGitHubData = data.items;  
  49.         console.log(this.nutaNixGitHubData);  
  50.     });  
  51.   }  
  52.   
  53.   numberOfPages(){  
  54.     return 10;  
  55.   };  
  56.   
  57.   private selectedValueObj(id: any) {  
  58.      this.ValueId = (id.srcElement || id.target).value;  
  59.      for (let i = 0; i < this.technologies.length; i++) {  
  60.        if (this.technologies[i].id == this.ValueId) {  
  61.          this.selectedObj = this.technologies[i];  
  62.          this.selectedName = this.selectedObj.name;  
  63.          this.getNutanixRepo();  
  64.         }  
  65.       }  
  66.     }  
  67.   
  68.     showDetails(id: any){  
  69.       console.log(id);  
  70.       this.router.navigate(['/detail', {'id': id}]);  
  71.   };  
  72. }  
Here, I have written some methods and made some service calls. I want to navigate from this "home" component to "details" component.
So, I have written one method like below.
  1. showDetails(id: any){  
  2.       console.log(id);  
  3.       this.router.navigate(['/detail', {'id': id}]);  
  4.   };  
The showDetails method just takes id as an argument and passes it to router.navigate. But, I did not mention in this method that where will it navigate. It will navigate to "details" component, just consider it. I will explain this ahead, in more details.
 
home.html
 
Binding and UI of home component will display on home.html file.
  1. <div>  
  2. <span>Please Select Technology:</span> <select [(ngModel)]="ValueId" (change)="selectedValueObj($event)">  
  3. <option  *ngFor="let Value of technologies" [value]="Value.id" >  
  4. {{Value.name}}</option></select>   
  5. </div>  
  6. <h3>List of Source Code Repository</h3>  
  7.  <div class="row">  
  8.  <div class="col-md-6" *ngFor="let nutanixData of nutaNixGitHubData" (click) ="showDetails(nutanixData.owner.login)">  
  9.      <div class="panel">  
  10.          <div class="panel-body panelbody">   
  11.              <div class="col-md-3"> <img src="{{nutanixData.owner.avatar_url}}"  
  12.               alt="avatar" height="200" width="180"></div>  
  13.              <div class="col-md-6">  
  14.                  <div> <span>ID: {{nutanixData.id}}</span> </div>  
  15.              <div> <span>Name: {{nutanixData.name}}</span> </div>  
  16.              <div> <span>Full name: {{nutanixData.full_name}}</span> </div>  
  17.              <div> <span>Owner Login: {{nutanixData.owner.login}}</span> </div>  
  18.              <div> <span>Owner ID: {{nutanixData.owner.id}}</span> </div>  
  19.              <div> <span>Url: <a href="{{nutanixData.owner.url}}">{{nutanixData.owner.url}}</a></span> </div>  
  20.              <div> <span>Type: {{nutanixData.owner.type}}</span> </div>  
  21.              <div> <span>Size: {{nutanixData.size}}</span> </div>  
  22.              <div> <span>No. of Forks: {{nutanixData.forks}}</span> </div>  
  23.              </div>  
  24.          </div>  
  25.      </div>  
  26.  </div>  
  27.  </div>  
  28.   
  29. t;div style="text-align: center; margin-bottom: 10px;" *ngIf="nutaNixGitHubData">  
  30.    <button [disabled] ="curPage == 1" (click)="prevPageClick()">PREV</button>  
  31.      <span>Page {{curPage}} of {{ numberOfPages() }}</span>  
  32.    <button [disabled] = "curPage >= 9" (click) ="currentPageClick()">NEXT</button>  
  33. lt;/div>     
In the above home.html file, I have defined method for navigation like below.
  1. <div class="col-md-6" *ngFor="let nutanixData of nutaNixGitHubData" (click) ="showDetails(nutanixData.owner.login)">   
home.routes.ts
 
This is the routing strategy file for "home" component.
  1. import { Routes } from '@angular/router';  
  2.   
  3. import { HomeListComponent }    from './home-list.component';  
  4.   
  5. export const homeRoutes: Routes = [  
  6.   { path: 'home', component: HomeListComponent }  
  7. ];  
In homeRoutes component, I have defined the path name "home" for the HomeListcomponent. This path name plays very important role in the navigation.
 
Now, I will move to another component.
 
Component "detail"
 
Another component, i.e., "detail" is navigated through "home" component. Create three different files one by one, like below.
 
detail.component.ts
 
The detail.component.ts is just another component. It renders when it is being navigated through home components.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { ActivatedRoute } from '@angular/router';  
  3. import { NutanixService } from '../dataservices/nutanix.service';  
  4. import { Observable } from 'rxjs/Observable;  
  5.   
  6. @Component({  
  7. templateUrl: './app/detail/repodetail.html'  
  8. })  
  9.   
  10. export class DetailComponent implements OnInit {  
  11.   private selectRepoOwner;  
  12.   nutaNixOwnerData: any;  
  13.   gitHubOwnerFollowers: any;  
  14.   
  15.   constructor(private route: ActivatedRoute, private nutanixervice: NutanixService) {}  
  16.   
  17.   ngOnInit() {  
  18.     this.sub = this.route.params.subscribe(params => {  
  19.       this.selectRepoOwner = params['id'];   
  20.       this.getNutOwneranixRepo();  
  21.       this.getGitOwnerFollowers();  
  22.     });  
  23.   }  
  24.   
  25.   getNutOwneranixRepo() {  
  26.     this.nutanixervice.getNutanixGitHubOwnerData(this.selectRepoOwner).subscribe(  
  27.       (data)=>{  
  28.         this.nutaNixOwnerData = data.items[0];  
  29.         console.log(this.nutaNixOwnerData);  
  30.     });  
  31.   }  
  32.   
  33.     getGitOwnerFollowers() {  
  34.     this.nutanixervice.getGitHubOwnerFollowers(this.selectRepoOwner).subscribe(  
  35.       (data)=>{  
  36.         this.gitHubOwnerFollowers = data;  
  37.         console.log(this.gitHubOwnerFollowers);  
  38.     });  
  39.   }  
  40. }  
If you observe closely to detail.component.ts file, you will find that I have imported the route below.
  1. import { ActivatedRoute } from '@angular/router';  
"ActivatedRouter" contains the information about a route associated with a component loaded in an outlet. 
 
Also, I have passed this route into this component's constructor like below.
  1. constructor(private route: ActivatedRoute) {}   
So OnInit, this detail component will call the below method.
  1. ngOnInit() {  
  2.    this.sub = this.route.params.subscribe(params => {  
  3.      this.selectRepoOwner = params['id'];   
  4.    });  
  5.  }  
route.params subscribes the navigation and gets the data from "params".
 
repodetail.html
 
This file is just the UI part of detail component.
 
detail.routes.ts
 
This file contains the routing strategy logic of detail component.
  1. import { Routes } from '@angular/router';  
  2.   
  3. import { DetailComponent }    from './detail.component';  
  4.   
  5. export const detailRoutes: Routes = [  
  6.   { path: 'detail', component: DetailComponent }  
  7. ];  
Here, this routing's path name is "detail". It is very important for routing. I will explain its usage and importance in the next code logic.
 
app.component.ts
 
This file contains the app level component routing links. Refer the below code for more details.
  1. import { Component, OnInit} from '@angular/core';  
  2.   
  3.   
  4. @Component({  
  5.   selector: 'my-app',  
  6.   template: `  
  7.   <div class="row">  
  8.     <h1 Style=margin-left:10px;>Nutanix - TechScan</h1>  
  9.   </div>  
  10.    <div>  
  11.      <nav>  
  12.      <a class="mdl-navigation__link" [routerLink]="['/']">Home</a>  
  13.     </nav>  
  14.     <hr>  
  15.     </div>  
  16.     <div>  
  17.       <router-outlet></router-outlet>  
  18.     </div>  
  19.   `,  
  20. })  
  21.   
  22. // App Component class  
  23. export class AppComponent{  
  24. }  
Here, <router-outlet></router-outlet> has been defined. It enables navigation from one View to the next on the request by user.
[routerLink] is used to define the routing path. 
 
app.routes.ts
 
This file contains app level routing strategy logic. It contains app level routing configuration detail.
  1. import { ModuleWithProviders }  from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3.   
  4. import { homeRoutes }    from './home/home.routes';  
  5. import { detailRoutes }    from './detail/detail.routes';  
  6.   
  7. // Route Configuration  
  8. export const routes: Routes = [  
  9.   {  
  10.     path: '',  
  11.     redirectTo: '/home',  
  12.     pathMatch: 'full'  
  13.   },  
  14.   ...homeRoutes,  
  15.   ...detailRoutes  
  16. ];  
  17.   
  18. export const routing: ModuleWithProviders = RouterModule.forRoot(routes);  
In the above code, I have defined both the component's routing name - ...homeRoutes, ...detailRoutes. By default, "homeRoutes" will be called on the load of the index.html file. And, "detailRoutes" will be called on the request performed by "home" component.
 
app.module.ts
 
This is the application level module file. It contains all the components, services, application level route details.
  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 { HomeListComponent } from './home/home-list.component';  
  8. import { DetailComponent } from './detail/detail.component';  
  9.   
  10. import { routing } from './app.routes';  
  11. import {NutanixService} from '../app/dataservices/nutanix.service';  
  12.   
  13. @NgModule({  
  14.   imports: [  
  15.     BrowserModule,  
  16.     FormsModule,  
  17.     HttpModule,  
  18.     JsonpModule,  
  19.     routing  
  20.   ],  
  21.   declarations: [  
  22.     AppComponent,  
  23.     HomeListComponent,  
  24.     DetailComponent  
  25.   ],  
  26.    providers: [  
  27.    NutanixService  
  28.   ],  
  29.   bootstrap: [ AppComponent ]  
  30. })  
  31.   
  32. export class AppModule {  
  33. }  
I have created one project that handles the routing and navigation from one component to another component. It basically fetches the "List of all source code repository" from GitHub based on the selection of different technologies mentioned below.

 

This is the "home" component. If the user clicks on any item, then it navigates to the "detail" component.

 

This is the "detail" component. It receives the "user data" from "home" component, navigates, and shows the related detail of the user.
 
I have attached the zipped project. You can download, unzip, and see the code. 
 
Step to Execute the App
  • Install and integrate Node.js
  • Internet should be available
  • Go to the root folder of the project -> e.g. D:\myapp\
  • Open the command prompt for this path.
  • Type command: npm start
  • Application will launch in the browser.

Conclusion

Angular 4 routing is a very powerful concept. It provides an easy and very robust mechanism to navigate and transfer the data from one component to another component.

Up Next
    Ebook Download
    View all
    Learn
    View all