Routing In Angular 2 With TypeScript And Visual Studio 2015 - Part One

In this article, we are going to learn how to implement routing in Angular 2 with example.

Routing is a concept which helps users to navigate from one view to another view of the application. Similarly, routing in Angular 2 helps users to navigate from one view to another view depending upon the URL which user enters in the browser. In component based architecture of Angular 2, Angular looks into the routes array, match the path as per the route requested and loads the component relevant to the requested route as well as makes available the relevant data for that particular route.

So, let’s look into some core concepts of Angular 2 routing step by step implementation below. Here I am using the same “StudentList” example which I have used in my previous articles so far. You can download the latest code from here.

Step 1. Route Configurations

Base Ref

First thing we need to add the base tag to the index.html file in the root folder src/index.html.

  1. <base href="/src/">  

Import Modules

We need to import two modules from ‘@angular/router’ library package for implementing the routing -

  1. import { Routes, RouterModule } from '@angular/router';  

Routes

The Routes is an array of routes objects defined for the Angular application. We need to make an array of Routes type and add the route objects inside the array. As route object, we set up the path and the components which we want to use for that particular path.

  1. export const routes: Routes = [  
  2.     { path: '', redirectTo: 'list-student', pathMatch: 'full' },  
  3.     { path: 'list-student', component: StudentListComponent },  
  4.     { path: 'course-list', component: CourseComponent }  
  5. ];  

Each route has many properties. Some of those properties are –

  1. Path – URL to be shown in the browser.
  2. Component – Component to be load when the application is on specific route.
  3. RedirectTo – Configure the route redirect to another route
  4. PathMatch – PathMatch property tells Angular how it should match the URL provided in order to redirect to specific route.
  5. Children – Tell the Angular about the child route objects on that particular route.
Router Module

To implement the routing in Angular 2, we need to import the router’s module into our application module to register the route objects. That is called RouterModule. To provide information about our routes or components or we can say like to define our route config, Angular RouteModule provides us two static methods –

  1. forRoot
    This is used when defining the route config for our application in our main module.
    1. export const routing = RouterModule.forRoot(routes);  
  1. forChild
    This is used for our featured/child modules rather than our main module and very similar to forRoot method. This is mainly used when we don’t allow to configure our all routes in only main (root) module. Instead, we allow our other modules to configure routes for themselves, which will be import into our main module if needed.
    1. export const routingCourses = RouterModule.forRoot(courseRoutes); 

Let’s take a look at code configuration together, and how we’d use this,

app.routes.ts

In src/app/app.routes.ts file, we imported routing modules for implementing routing, imported “StudentList” component as well as “CourseComponent”, created routes config with path and component properties and register it with forRoot method of RouterModule. Look at the highlighted lines below, 

  1. import { Routes, RouterModule } from '@angular/router';  
  2. import { StudentListComponent } from './student/student.component';  
  3. import { CourseComponent } from './course/course.component';  
  4.   
  5. export const routes: Routes = [  
  6.     { path: '', redirectTo: 'list-student', pathMatch: 'full' },  
  7.     { path: 'list-student', component: StudentListComponent },  
  8.     { path: 'course-list', component: CourseComponent }  
  9. ];  
  10.   
  11. export const routing = RouterModule.forRoot(routes);  

Note

When our application will start, it will navigate to the empty route by default. We configured the router to redirect to a “list-student” route by default using “redirectTo” property.

app.component.ts

In src/app/app.component.ts file, we imported our routing module (which we created above) inside our main application module. Look at the highlighted lines below, 

  1. import { NgModule }      from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { routing } from './app.routes' 
  4.   
  5. import { AppComponent } from './app.component';  
  6. import { StudentListComponent } from './student/student.component';  
  7. import { courseCategoryPipe } from './student/student.coursepipe';  
  8. import { SearchBarComponent } from './Shared/SearchBar/searchbar.component';  
  9. import { CourseComponent } from './course/course.component';  
  10.   
  11. @NgModule({  
  12.     imports: [BrowserModule, routing],  
  13.     declarations: [AppComponent, StudentListComponent, courseCategoryPipe, SearchBarComponent, CourseComponent],  
  14.   bootstrap:    [ AppComponent ]  
  15. })  
  16. export class AppModule { }  

Step 2. Displaying Routes

Router-Outlet

Once routes configuration is done, now we need to tell Angular where the components will be loaded. This is done by using a directive “router-outlet”. When the router matches the route and found the component to be load, it will dynamically inject the component inside the router-outlet directive.

  1. <router-outlet></router-outlet>  

 

RouterLink

To create links to the routes, we use “routerLink” directive in Angular 2 routing like below,

  1. <a routerLink="/list-student">Student List</a>  

Navigating Programmatically

To navigate programmatically to a route, we use navigate function in Angular 2 like below –

  1. this.router.navigate(['/course-list']);  

In app.component.html file, we have added the “router-outlet” directive as shown below –

app.component.html

  1. <ul class="nav nav-pills">  
  2.     <li class="active"><a routerLink="/list-student">Student List</a></li>  
  3.     <li><a routerLink="/course-list">Course List</a></li>  
  4. </ul>  
  5. <br/>  
  6. <router-outlet></router-outlet>  
Now, we have implemented the main building blocks for setting up the router in Angular 2 application. 

Step 3. Components and Templates

As of now we have established the routes, registered them with “RouterModule” and imported them into our main application module. Now, we will take a quick look at components code and their functionalities and will run the project to get the expected output –

  • student.component.ts
    1. import { Component, OnInit} from '@angular/core'  
    2.   
    3. @Component({  
    4.     selector: 'list-student',  
    5.     templateUrl: 'app/student/student.component.html'  
    6. })  
    7. export class StudentListComponent implements OnInit {  
    8.   
    9.     students: any[];  
    10.   
    11.     public LoadStudents(filterText: string): void {  
    12.         this.students = [  
    13.             { studentID: 1, studentName: 'Steve', gender: 'Male', age: 35, course: 'MCA', DOB: '10/12/1982', grade:0.7500,rating:7.5123 },  
    14.             { studentID: 2, studentName: 'Bobby', gender: 'Male', age: 32, course: 'MBA', DOB: '12/1/1985', grade: 0.7850, rating: 7.8223 },  
    15.             { studentID: 3, studentName: 'Rina', gender: 'Female', age: 45, course: 'B.Tech', DOB: '9/11/1972', grade: 0.8525, rating: 8.5263 },  
    16.             { studentID: 4, studentName: 'Alex', gender: 'Female', age: 24, course: 'M.Tech', DOB: '1/1/1993', grade: 0.5540, rating: 5.5123 },  
    17.             { studentID: 5, studentName: 'Rahul', gender: 'Male', age: 26, course: 'MCA', DOB: '1/21/1991', grade: 0.9550, rating: 9.5534 },  
    18.         ];  
    19.   
    20.         if (filterText != "") {  
    21.             var filterStudentList: any[] = [];  
    22.             this.students.forEach(stu => {  
    23.                 if (stu.studentName.toLowerCase().includes(filterText)) {  
    24.                     filterStudentList.push(stu);  
    25.                 }  
    26.             })  
    27.             this.students = filterStudentList;  
    28.         }  
    29.     }  
    30.   
    31.     ngOnInit() {  
    32.         this.LoadStudents("");  
    33.     }  
    34.   
    35.     OnStudentSearch(searchTerm: string): void {  
    36.         this.LoadStudents(searchTerm);  
    37.     }  
    38. }  
  • student.component.html
    1. <search-bar (Search)="OnStudentSearch($event)"></search-bar>  
    2. <table class="table table-responsive table-bordered table-striped">  
    3.     <thead>  
    4.         <tr>  
    5.             <th>Student ID</th>  
    6.             <th>Name</th>  
    7.             <th>Gender</th>  
    8.             <th>Age</th>  
    9.             <th>Course</th>   
    10.             <th>DOB</th>     
    11.             <th>Grade</th>   
    12.             <th>Rating</th>           
    13.         </tr>  
    14.     </thead>  
    15.     <tbody>  
    16.         <tr *ngFor="let s of students;">  
    17.             <td>{{s.studentID}}</td>  
    18.             <td>{{s.studentName | uppercase}}</td>  
    19.             <td>{{s.gender | lowercase}}</td>  
    20.             <td>{{s.age}}</td>  
    21.             <td>{{s.course | courseCategory}}</td>  
    22.             <td>{{s.DOB | date:'yMMMMd' | uppercase }}</td>  
    23.             <td>{{s.grade | percent:'.2'}}</td>  
    24.             <td>{{s.rating | number:'2.1-2'}}</td>  
    25.         </tr>  
    26.     </tbody>  
    27. </table>  
  • course.component.ts
    1. import { Component, OnInit } from '@angular/core'  
    2.   
    3. @Component({  
    4.     selector: 'course-list',  
    5.     templateUrl:'app/course/course.component.html'  
    6. })  
    7. export class CourseComponent implements OnInit {  
    8.     courseList: any[];  
    9.   
    10.     getCourses(): void {  
    11.         this.courseList = [  
    12.             { courseID: 101, courseName: 'BCA', category: 'IT' },  
    13.             { courseID: 102, courseName: 'MCA', category: 'IT' },  
    14.             { courseID: 103, courseName: 'MBA', category: 'MANAGEMENT' },  
    15.             { courseID: 104, courseName: 'B.TECH', category: 'CS' },  
    16.             { courseID: 105, courseName: 'B.ARCH', category: 'ARCHITECTURE' },  
    17.             { courseID: 106, courseName: 'BBA', category: 'MANAGEMENT' },  
    18.         ];  
    19.     }  
    20.   
    21.     ngOnInit() {  
    22.         this.getCourses();  
    23.     }  
    24. }  
  • course.component.html
    1. <table class="table table-responsive table-bordered table-striped">  
    2.     <thead>  
    3.         <tr>  
    4.             <th>Course ID</th>  
    5.             <th>Name</th>  
    6.             <th>Category</th>  
    7.         </tr>  
    8.     </thead>  
    9.     <tbody>  
    10.         <tr *ngFor="let s of courseList;">  
    11.             <td>{{s.courseID}}</td>  
    12.             <td>{{s.courseName | uppercase}}</td>  
    13.             <td>{{s.category}}</td>  
    14.         </tr>  
    15.     </tbody>  
    16. </table>  
Project Templates and Component Structure


Step 4. Run the project

Build the project and run by pressing Ctrl + F5. And now you will see the output as below,

output

Summary

In this article, we covered the following topics - 

  • What is Routing in Angular 2 and what are the main building block of Angular 2 routing?
  • How routes are configured in Angular 2 routing?
  • What are router-outlet and rouerLink in Angular 2 routing?
  • Step by step routing configuration in student application

To read more articles on Angular 2, please check out the below links - 

Write to me in the comment box in case you need any help or you have any questions or concerns. Have a good day!

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now