Introduction To Routing In Angular 2

Routing is a process of changing the state of your Application by loading different components depending upon the URL that the user enters. Angular 2 parses the entered URL by the user and try to identify the routes according the different segments of URL. In this article, we learn how routing works in Angular2. We will create an app, where we have two sections, Home and Student. When we click on Student section; a list of the students will open further, when we click on a student name; we display all the details of that student. Let’s start today’s section.

We will create three components in this Application. Home will be the home page for our student dashboard, student-list component will contain the list of all the students and last one is student component that will display the information of a particular student.

Thus, create three components “home”, “student” and “student-list”.


To perform the routing in our Application, we need to define the routes. First, we create a route file in “app” folder that will contain the routes of our Application. Create a “app.routes.ts” file in “app” folder and insert the code given below into “app.routes.ts” file. 

  1. import {RouterModule,Routes} from '@angular/router';  
  2. import {HomeComponent} from './home/home.component';  
  3. import {StudentListComponent} from './student-list/student-list.component';  
  4. import {StudentComponent} from './student/student.component';  
  5. const APP_ROUTES:Routes=[  
  6.     {path:'',component:HomeComponent},  
  7.     {path:'student',component:StudentListComponent},  
  8.     {path:'student/:id',component:StudentComponent}  
  9. ];  
  10.   
  11. export const Routes_Provider=RouterModule.forRoot(APP_ROUTES);  

In the code given above, we import home, student and student-list components that we created earlier. Here, we create a “APP_ROUTES” constant of routes type. This constant contains all the routes, which we require. Path property contains the routes that we want to match and component property defines the component that will be called when the path matches the routes value. In the next line, we define another constant variable. This variable contains the result generated from “RouterModule.forRoot” method. RouterModule.forRoot method creates a module that contains all the Directives, the given routes and the router Service itself.

After creating all the required routes, we need to configure these routes at the root level of the Application. Now, go to “app.modules.ts” file and import the routes file that we created earlier.

App.Modules.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5.   
  6. import { AppComponent } from './app.component';  
  7. import { HomeComponent } from './home/home.component';  
  8. import { StudentComponent } from './student/student.component';  
  9. import { StudentListComponent } from './student-list/student-list.component';  
  10. import {Routes_Provider} from 'app/app.routes';  
  11.   
  12. @NgModule({  
  13.   declarations: [  
  14.     AppComponent,  
  15.     HomeComponent,  
  16.     StudentComponent,  
  17.     StudentListComponent,  
  18.     HomeComponent  
  19.   ],  
  20.   imports: [  
  21.     BrowserModule,  
  22.     FormsModule,  
  23.     HttpModule,  
  24.     Routes_Provider  
  25.   ],  
  26.   providers: [],  
  27.   bootstrap: [AppComponent]  
  28. })  
  29. export class AppModule { }  

Angular is used to create the “SPA” Application, so we follow this convention in our Application. We require a “home” button. Using it, we can navigate to home section of the Application and “studentList” button, using which we can navigate to studentList section of the Application. When we click on any student name, then student section will display the information of that particular student. We will create a common header, which will display on all the sections of our Application.

Now, write the code given below in “app.component.html” page.

  1. <h1>  
  2.   {{title}}  
  3. </h1>  
  4. <ul>  
  5.   <!--<li><a href="/">Home</a></li>  
  6.   <li><a href="/student">Student List</a></li>-->  
  7.    <li><a [routerLink]="['']">Home</a></li>  
  8.   <li><a [routerLink]="['student']">Student List</a></li>  
  9. </ul>  
  10. <router-outlet></router-outlet>  

In the code given above, we create two anchor tags for Home and Student List. Instead of “href” attribute of anchor tag, we use the “routerLink” attribute of Angular. The routerLink attribute allows us to link to a specific route of the Application. In the last line of this page, we use the “router-outlet” Angular Directive. This Directive acts as a placeholder that is dynamically filled by Angular and is based on the current router state. This is the section, where we display the content of the components, which are based on the route value.

Now, our setup is ready. Let’s move to our component sections.

Home.component.html

  1. <p>  
  2.  This is Home Page,<br/> click On Student List for Student Information.  
  3. </p>  

In home component, we are displaying only some text information. Let’s move to our student-list component.

Student-list.component.html

  1. <ul>  
  2. <li *ngFor="let data of studentList">  
  3.    <a [routerLink]="['/student/',data.id]"> {{data.name}}</a>  
  4.   </li>  
  5. </ul>  

Student-list.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-student-list',  
  5.   templateUrl: './student-list.component.html',  
  6.   styleUrls: ['./student-list.component.css']  
  7. })  
  8.   
  9. export class StudentListComponent implements OnInit {  
  10. public studentList:student[]=[];  
  11.   
  12.   constructor() {  
  13.   
  14.   this.studentList=[  
  15.                   new student(100,"Pankaj Choudhary"),  
  16.                   new student(101,"Sandeep Jangid"),  
  17.                   new student(102,"Rahul Prajapat"),  
  18.                   new student(103,"Sanjeev Baldia")];  
  19.    }  
  20.   
  21.   ngOnInit() {  
  22.   }  
  23.   
  24. }  
  25.   
  26. class student{  
  27. id:number;  
  28. name:string;  
  29. constructor(id:number,name:string){  
  30.   this.id=id;  
  31.   this.name=name;  
  32. }  
  33. }   

In student-list component, we will create a “studentList” array object of student type. In constructor function, we will insert some information of the student in this array object. In the template section of this component, we use the “ngFor” directives to create a list of the students and also create an anchor tag for each value of the “studentList” list. In “routerLink” Directive, we define two segments “/student/” and data.id, which are similar to “/student/data.id” of an anchor tag and match the ‘student/:id’ route of our route file. For example, when we click for “Sanjeev Baldia” student “localhost:4200/sudent/103” URL will generate when 103 is the Id of this student. Now, we move to student component, which is the most important segment of this Application.

Student.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { ActivatedRoute } from '@angular/router';  
  3. @Component({  
  4.   selector: 'app-student',  
  5.   templateUrl: './student.component.html',  
  6.   styleUrls: ['./student.component.css']  
  7. })  
  8. export class StudentComponent implements OnInit {  
  9. public studentList:student[]=[  
  10.                   new student(100,"Pankaj Choudhary","P-20 Gandhi Nagar Alwar","Software Developer"),  
  11.                   new student(101,"Sandeep Jangid","G14 Vasant Vihar , Jaipur","Electrical Enginner"),  
  12.                   new student(102,"Rahul Prajapat","K1-104, CR Park Delhi","DBA"),  
  13.                   new student(103,"Sanjeev Baldia","D-19, Malviya Nagar, Jaipur","Sales Head")];  
  14.   
  15. public studentInfo:student;  
  16. public studentId:number;  
  17.   constructor(private route: ActivatedRoute)   
  18.   {  
  19.     this.route.params.subscribe(params=>{  
  20.       this.studentId=params['id'];  
  21.   });  
  22.   
  23.     this.studentInfo=this.studentList.find(x=>x.id==this.studentId);  
  24.    }  
  25.   
  26.   ngOnInit() {  
  27.   }  
  28.   
  29. }  
  30. class student{  
  31. id:number;  
  32. name:string;  
  33. address:string;  
  34. jobProfile:string;  
  35.   
  36. constructor(id:number,name:string,address:string,jobProfile:string){  
  37.   this.id=id;  
  38.   this.name=name;  
  39.   this.address=address;  
  40.   this.jobProfile=jobProfile;  
  41. }  
  42. }  

In the code given above, we create a “studentList” array object of student class type. This object contains same students information, which we created in “student-list” component but with two extra properties “address” and “jobProfile”. We import the “ActivatedRoute” interface in this component. ActivatedRoute contains the information about a route associated with a component loaded in an outlet. An ActivatedRoute can also be used to traverse the router state tree.

  1. constructor(private route: ActivatedRoute)   
  2.   {  
  3.     this.route.params.subscribe(params=>{  
  4.       this.studentId=params['id'];  
  5.   });  

In the line of code given above, we define route property of ActivatedRoute type. ActivatedRoute comes with a params property i.e. Observable. If you are not aware of Observable and Promises, then don’t worry, as I will cover these topics in my upcoming articles. Observable is like a stream and allows us to pass the events, where the callback is called for each event. Subscribe is the function that is called when the Observable is initially subscribed to. This function is given a Subscriber to which new values can be `next`ed, or an `error` method can be called to raise an error or `complete` can be called to notify of a successful completion. On the completion, we are getting the value of “id” parameter, which we passed from the student-list component.

 

  1. this.studentInfo=this.studentList.find(x=>x.id==this.studentId);  

 

In the lines of code, we are getting the student information, whose id is similar to the id, which we fetched out from the URL and insert into “studentInfo” object.

Student.component.html 

  1. <h2>  
  2.   Student Information  
  3. </h2>  
  4. <div>  
  5.  <table>  
  6.    <tr>  
  7.      <td>Student Name : </td>  
  8.        
  9.      <td>{{studentInfo.name}}</td>  
  10.        
  11.      </tr>  
  12.    <tr>  
  13.       <td>Address : </td>  
  14.     
  15.      <td>{{studentInfo.address}}</td>  
  16.    </tr>  
  17.    <tr>  
  18.       <td>Job Profile : </td>  
  19.       
  20.      <td>{{studentInfo.jobProfile}}</td>  
  21.    </tr>  
  22.  </table>  
  23. </div>   

Student.component.css

  1. table {  
  2.     border-collapse: collapse;  
  3.     width: 50%;  
  4. }  
  5.   
  6. th, td {  
  7.     text-align: left;  
  8.     padding: 8px;  
  9. }  
  10.   
  11. tr:nth-child(even){background-color: #f2f2f2}  
  12. th, td {  
  13.     border: 1px solid #ddd;  
  14. }   

In the lines of code given above, we are displaying the information of a student and apply some CSS. Now, our setup is ready. Let’s run the Application.


This is the home screen of our Application. When we click on “Student List” menu item, then this screen will be displayed.


In this screen, we can see the list of all the students. Afterwards, click on any student name and we can get the information of that particular student.


We cover the basics of Angular 2 routing. Now, let’s consider some other points in Angular 2 routing:

Double Star(**) Path

What if any user inserts a URL that doesn’t match any route defined in route file. In such case, we will get the error, as shown below.


To prevent this error, we need to define the default route in our route file, as shown below.


The “**” must be the last route in the route list. The router selects this route automatically, if the requested URL doesn’t match any routes. We can use the routes to display our home or “404- Not found” page.

Triggered Routing from back-end

Till now, we triggered the routing, using the anchor tag. Now, learn how to trigger the routing from back-end code. In “student.component.html” page, add a button and on click, we will be redirected from the student details to student list page.


  1. <h2>  
  2.   Student Information  
  3. </h2>  
  4. <div>  
  5.  <table>  
  6.    <tr>  
  7.      <td>Student Name : </td>  
  8.        
  9.      <td>{{studentInfo.name}}</td>  
  10.        
  11.      </tr>  
  12.    <tr>  
  13.       <td>Address : </td>  
  14.     
  15.      <td>{{studentInfo.address}}</td>  
  16.    </tr>  
  17.    <tr>  
  18.       <td>Job Profile : </td>  
  19.       
  20.      <td>{{studentInfo.jobProfile}}</td>  
  21.    </tr>  
  22.  </table>  
  23. </div>  
  24. <br/>  
  25. <input type="button" value="Student List" (click)=Navigate() />   

In the lines of code given above, we add a “Student List” button and on click event, we are calling “Navigate()” function.

Student.component.ts 

  1. import { Component, OnInit } from '@angular/core';  
  2. import { ActivatedRoute,Router } from '@angular/router';  
  3. @Component({  
  4.   selector: 'app-student',  
  5.   templateUrl: './student.component.html',  
  6.   styleUrls: ['./student.component.css']  
  7. })  
  8. export class StudentComponent implements OnInit {  
  9. public studentList:student[]=[  
  10.                   new student(100,"Pankaj Choudhary","P-20 Gandhi Nagar Alwar","Software Developer"),  
  11.                   new student(101,"Sandeep Jangid","G14 Vasant Vihar , Jaipur","Electrical Enginner"),  
  12.                   new student(102,"Rahul Prajapat","K1-104, CR Park Delhi","DBA"),  
  13.                   new student(103,"Sanjeev Baldia","D-19, Malviya Nagar, Jaipur","Sales Head")];  
  14.   
  15. public studentInfo:student;  
  16. public studentId:number;  
  17.   constructor(private route: ActivatedRoute, private router:Router)   
  18.   {  
  19.     this.route.params.subscribe(params=>{  
  20.       this.studentId=params['id'];  
  21.   });  
  22.   
  23.     this.studentInfo=this.studentList.find(x=>x.id==this.studentId);  
  24.    }  
  25.   
  26. public Navigate(){  
  27.   this.router.navigate(['/student']);  
  28. }  
  29.   
  30.   ngOnInit() {  
  31.   }  
  32.   
  33. }  
  34. class student{  
  35. id:number;  
  36. name:string;  
  37. address:string;  
  38. jobProfile:string;  
  39.   
  40. constructor(id:number,name:string,address:string,jobProfile:string){  
  41.   this.id=id;  
  42.   this.name=name;  
  43.   this.address=address;  
  44.   this.jobProfile=jobProfile;  
  45. }  
  46. }  

In the code given above, we import the “Router” class and using the Navigate method of this class, we can update the URL without refreshing the page. Hence, when we click on “Student List” button, we will move to the Student list segment of the Application.

Conclusion

In this article, we learned about routing in Angular and also, learned how they work. I hope, you liked this article. In the next article, I will cover another topic of Angular 2. 


Similar Articles