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.
- import {RouterModule,Routes} from '@angular/router';
- import {HomeComponent} from './home/home.component';
- import {StudentListComponent} from './student-list/student-list.component';
- import {StudentComponent} from './student/student.component';
- const APP_ROUTES:Routes=[
- {path:'',component:HomeComponent},
- {path:'student',component:StudentListComponent},
- {path:'student/:id',component:StudentComponent}
- ];
-
- 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
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
-
- import { AppComponent } from './app.component';
- import { HomeComponent } from './home/home.component';
- import { StudentComponent } from './student/student.component';
- import { StudentListComponent } from './student-list/student-list.component';
- import {Routes_Provider} from 'app/app.routes';
-
- @NgModule({
- declarations: [
- AppComponent,
- HomeComponent,
- StudentComponent,
- StudentListComponent,
- HomeComponent
- ],
- imports: [
- BrowserModule,
- FormsModule,
- HttpModule,
- Routes_Provider
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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.
- <h1>
- {{title}}
- </h1>
- <ul>
- <!--<li><a href="/">Home</a></li>
- <li><a href="/student">Student List</a></li>-->
- <li><a [routerLink]="['']">Home</a></li>
- <li><a [routerLink]="['student']">Student List</a></li>
- </ul>
- <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
- <p>
- This is Home Page,<br/> click On Student List for Student Information.
- </p>
In home component, we are displaying only some text information. Let’s move to our student-list component.
Student-list.component.html
- <ul>
- <li *ngFor="let data of studentList">
- <a [routerLink]="['/student/',data.id]"> {{data.name}}</a>
- </li>
- </ul>
Student-list.component.ts
- import { Component, OnInit } from '@angular/core';
-
- @Component({
- selector: 'app-student-list',
- templateUrl: './student-list.component.html',
- styleUrls: ['./student-list.component.css']
- })
-
- export class StudentListComponent implements OnInit {
- public studentList:student[]=[];
-
- constructor() {
-
- this.studentList=[
- new student(100,"Pankaj Choudhary"),
- new student(101,"Sandeep Jangid"),
- new student(102,"Rahul Prajapat"),
- new student(103,"Sanjeev Baldia")];
- }
-
- ngOnInit() {
- }
-
- }
-
- class student{
- id:number;
- name:string;
- constructor(id:number,name:string){
- this.id=id;
- this.name=name;
- }
- }
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
- import { Component, OnInit } from '@angular/core';
- import { ActivatedRoute } from '@angular/router';
- @Component({
- selector: 'app-student',
- templateUrl: './student.component.html',
- styleUrls: ['./student.component.css']
- })
- export class StudentComponent implements OnInit {
- public studentList:student[]=[
- new student(100,"Pankaj Choudhary","P-20 Gandhi Nagar Alwar","Software Developer"),
- new student(101,"Sandeep Jangid","G14 Vasant Vihar , Jaipur","Electrical Enginner"),
- new student(102,"Rahul Prajapat","K1-104, CR Park Delhi","DBA"),
- new student(103,"Sanjeev Baldia","D-19, Malviya Nagar, Jaipur","Sales Head")];
-
- public studentInfo:student;
- public studentId:number;
- constructor(private route: ActivatedRoute)
- {
- this.route.params.subscribe(params=>{
- this.studentId=params['id'];
- });
-
- this.studentInfo=this.studentList.find(x=>x.id==this.studentId);
- }
-
- ngOnInit() {
- }
-
- }
- class student{
- id:number;
- name:string;
- address:string;
- jobProfile:string;
-
- constructor(id:number,name:string,address:string,jobProfile:string){
- this.id=id;
- this.name=name;
- this.address=address;
- this.jobProfile=jobProfile;
- }
- }
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.
- constructor(private route: ActivatedRoute)
- {
- this.route.params.subscribe(params=>{
- this.studentId=params['id'];
- });
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.
- 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
- <h2>
- Student Information
- </h2>
- <div>
- <table>
- <tr>
- <td>Student Name : </td>
-
- <td>{{studentInfo.name}}</td>
-
- </tr>
- <tr>
- <td>Address : </td>
-
- <td>{{studentInfo.address}}</td>
- </tr>
- <tr>
- <td>Job Profile : </td>
-
- <td>{{studentInfo.jobProfile}}</td>
- </tr>
- </table>
- </div>
Student.component.css
- table {
- border-collapse: collapse;
- width: 50%;
- }
-
- th, td {
- text-align: left;
- padding: 8px;
- }
-
- tr:nth-child(even){background-color: #f2f2f2}
- th, td {
- border: 1px solid #ddd;
- }
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.
- <h2>
- Student Information
- </h2>
- <div>
- <table>
- <tr>
- <td>Student Name : </td>
-
- <td>{{studentInfo.name}}</td>
-
- </tr>
- <tr>
- <td>Address : </td>
-
- <td>{{studentInfo.address}}</td>
- </tr>
- <tr>
- <td>Job Profile : </td>
-
- <td>{{studentInfo.jobProfile}}</td>
- </tr>
- </table>
- </div>
- <br/>
- <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
- import { Component, OnInit } from '@angular/core';
- import { ActivatedRoute,Router } from '@angular/router';
- @Component({
- selector: 'app-student',
- templateUrl: './student.component.html',
- styleUrls: ['./student.component.css']
- })
- export class StudentComponent implements OnInit {
- public studentList:student[]=[
- new student(100,"Pankaj Choudhary","P-20 Gandhi Nagar Alwar","Software Developer"),
- new student(101,"Sandeep Jangid","G14 Vasant Vihar , Jaipur","Electrical Enginner"),
- new student(102,"Rahul Prajapat","K1-104, CR Park Delhi","DBA"),
- new student(103,"Sanjeev Baldia","D-19, Malviya Nagar, Jaipur","Sales Head")];
-
- public studentInfo:student;
- public studentId:number;
- constructor(private route: ActivatedRoute, private router:Router)
- {
- this.route.params.subscribe(params=>{
- this.studentId=params['id'];
- });
-
- this.studentInfo=this.studentList.find(x=>x.id==this.studentId);
- }
-
- public Navigate(){
- this.router.navigate(['/student']);
- }
-
- ngOnInit() {
- }
-
- }
- class student{
- id:number;
- name:string;
- address:string;
- jobProfile:string;
-
- constructor(id:number,name:string,address:string,jobProfile:string){
- this.id=id;
- this.name=name;
- this.address=address;
- this.jobProfile=jobProfile;
- }
- }
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.