Home » Framework » Angular » How to use Routing and its functionalities in Angular

How to use Routing and its functionalities in Angular

This article explains how to use routing and its functionalities in angular applications. Let us see the below functionalities of routing in angular application.

  1. What is Routing?
  2. How to enable Routing?
  3. Create Routes.
  4. Redirecting and Wildcard Routes.
  5. Create Nesting Routes (Child Routes).
  6. Pass parameters in URL and Get parameters from URL.
  7. Create Relative Paths and Relative Route.

What is Routing in Angular Application?

Navigation between the pages is called routing in angular application. Here pages are in a form of components so we can say navigation between one component's view to another component's view is called routing.

How to enable Routing?

Create the new angular project named 'angular-routing' by using the command ng new angular-routing. While creating, it asks the questions like Would you like to add Angular Routing?. You can say yes by typing 'y' in the command prompt. That's it now your application is with routing enabled.

Here I have used the angular CLI version 12.0.5. In some lower versions of angular CLI, the above question will not be asked so we have to create the routing manually in that situation.

Now you can see the routing module under the app folder named 'app-routing.module.ts' like below

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [  
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This routing module is registered in the app.module.ts file by importing the routing module in the imports:[] array of @NgModule decorator.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent,   
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now we have to create routes in angular application.

Creating route in Angular Application

We have to create the navigation between the pages by declaring the path and the corresponding component in the routing module. For creating navigation we need at least two components in angular application. Let us create that first.

Before creating the components let us create one service to supply the data for all the components.

ng g service studentservice

The above command creates the service named StudentserviceService under the app folder. Now open the file studentservice.service.ts and do the changes like below.

studentservice.service.ts

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class StudentserviceService {
  studentList = [
    {"id":1,"name":"Salman","age":25,"gender":"MALE"},
    {"id":2,"name":"Sankar","age":30,"gender":"MALE"},
    {"id":3,"name":"Shivani","age":19,"gender":"FEMALE"},
    {"id":4,"name":"John","age":28,"gender":"MALE"},
    {"id":5,"name":"Roshini","age":30,"gender":"FEMALE"}
  ];
  subjectList = [
    {"id":"MAT1","name":"MATHEMATICS"},
    {"id":"PHY1","name":"PHYSICS"},
    {"id":"CHE1","name":"CHEMISTRY"},
    {"id":"BIO1","name":"BIOLOGY"},
    {"id":"ZOO1","name":"ZOOLOGY"},    
  ];
  constructor() { }
  getStudentList(){
    return this.studentList;
  }
  getSubjectList(){
    return this.subjectList;
  }
}

We can inject the above service into any of the components to get the data of students and subjects.

Now let us create the component named 'studentlist' by using the below command

ng g c studentlist

Now do the changes in the below files of studentlist component.

studentlist.component.html

<div>
  <table border="1">
    <thead>
      <th>Id</th>
      <th>Name</th>
      <th>Age</th>
      <th>Gender</th>      
    </thead>
    <tr *ngFor="let student of studentList">
      <td>{{student.id}}</td>
      <td>{{student.name}}</td>
      <td>{{student.age}}</td>
      <td>{{student.gender}}</td>    
    </tr>
  </table>
</div>

studentlist.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentserviceService } from '../studentservice.service';
@Component({
  selector: 'app-studentlist',
  templateUrl: './studentlist.component.html',
  styleUrls: ['./studentlist.component.css']
})
export class StudentlistComponent implements OnInit {
  studentList:any;
  constructor(private studentservice: StudentserviceService) { }
  ngOnInit(): void {
    this.studentList = this.studentservice.getStudentList();
  }
}

The above component gets the data of students from the service and displays it in the component's view.

Let us create one more component named 'subjects' by using the below command

ng g c subjects

Do the changes in the below files of subjects component

subjects.component.html

<div>
    <table border="1">
      <thead>
        <th>Id</th>
        <th>Subject Name</th>          
      </thead>
      <tr *ngFor="let subject of subjectList">
        <td>{{subject.id}}</td>
        <td>{{subject.name}}</td>        
      </tr>
    </table>
</div>

subjects.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentserviceService } from '../studentservice.service';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
  selector: 'app-subjects',
  templateUrl: './subjects.component.html',
  styleUrls: ['./subjects.component.css']
})
export class SubjectsComponent implements OnInit {
  subjectList:any;
  constructor(private studentService: StudentserviceService) { }
  ngOnInit(): void {
    this.subjectList = this.studentService.getSubjectList();
  } 
}

The above component gets the data of subjects from the service and displays it in the component's view.

Now let us define the path and the corresponding component in the routing module.

Define the path in the Routes array of Routing Module like below.

const routes: Routes = [
  {path:'studentlist', component:StudentlistComponent},  
  {path:'subjects', component:SubjectsComponent}
];

and import the components like below.

import { StudentlistComponent } from './studentlist/studentlist.component';
import { SubjectsComponent } from './subjects/subjects.component';

From the above configuration, the path 'http://localhost:4200/studentlist' displays the studentlist component's view template. It displays the list of students in the table.

The path 'http://localhost:4200/subjects' displays the subjects component's view template. It displays the list of subjects in tabular format.

Finally, the code of the app-routing.module.ts file looks like below.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StudentlistComponent } from './studentlist/studentlist.component';
import { SubjectsComponent } from './subjects/subjects.component';
const routes: Routes = [
  {path:'studentlist', component:StudentlistComponent},  
  {path:'subjects', component:SubjectsComponent}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now add the links for both the pages in the app.component.html file like below.

app.component.html

<h1>Welcome To TipsToCode!.</h1>
<div>
  <span><a routerLink="/studentlist">Student List</a></span>
  <span>  |  </span>
  <span><a routerLink="/subjects">Subject List</a></span>
</div>
<router-outlet></router-outlet>

Let's run the application and go to the URL 'http://localhost:4200/studentlist' in the browser to see the below result.

angular-routing-navigation

Redirecting and Wildcard routes

If we want to use a redirect in the angular application then we have to set the path and the redirect component. If the path matches then it redirects to the component's view that we mentioned.

Actually, we run the application now and check this URL 'http://localhost:4200/' in the browser. It displays only the navigation link in the app.component.html

routing-root-level

But we can load any component's view by default at the root level by setting up the redirect like below.

const routes: Routes = [
  {path:'studentlist', component:StudentlistComponent},  
  {path:'subjects', component:SubjectsComponent},
  {path:'', redirectTo:"/studentlist", pathMatch:'full'}
];

Now if we go to the URL 'http://localhost:4200' then it loads the StudentlistComponent view at the root level with that navigation link.

routing-with-redirect

Wildcard Routes

We can use wildcard routes to display a 404 page in the angular application. For example, if a user navigates the URL that doesn't exist in the application then it shows the 404 pages not found error. The well-established application handles this like redirecting to some page when the URL doesn't exist.

Now we can use these wildcard routes to redirect the users to the particular component. For that, we have to create the component named 'pagenotfound' by using the below command.

ng g c pagenotfound

Now open the file pagenotfound.component.html file and do the changes like below.

<p>Sorry!. This page URL is not avialable</p>

Setting up the wildcard route in the routing module like below.

const routes: Routes = [
  {path:'studentlist', component:StudentlistComponent},  
  {path:'subjects', component:SubjectsComponent},
  {path:'', redirectTo:"/studentlist", pathMatch:'full'},
  {path:"**", component:PagenotfoundComponent}
];

Actually, this wildcard route should be declared at last in the Routes array. Now the application matches the requested URL with the above paths of wildcard path. If no one matches then it displays the view of PagenotfoundComponent.

You can see the result by putting the URL in the browser that doesn't exist in the application. For example, If you try this URL 'http://localhost:4200/works' then it displays the message 'Sorry!. This page URL is not available in the browser.

Create Nesting (or) Child Routes in Angular Application

Nesting (or) child routes are used to create the routes that are related to a particular component other than your root component. Generally, the big application doesn't maintain all the routes at the root level instead it keeps the main components at the root level and keeps the sub-components at the child level.

For example, in our application, we have created two components studentlist and subjects right. Now if we want to create one more component to edit the student info then we don't need to create that as the root level instead we can create that component inside the studentlist component and navigates with the child route.

Let us create the component named 'editstudent' under the folder 'app/studentlist' by using the below command.

ng g c studentlist/editstudent

Now create the child route within the route 'studentlist' like below in the app-routing.module.ts.

const routes: Routes = [
  {path:'studentlist', component:StudentlistComponent, children:[{path:'editstudent', component:EditstudentComponent}]},  
  {path:'subjects', component:SubjectsComponent},
  {path:'', redirectTo:"/studentlist", pathMatch:'full'},
  {path:"**", component:PagenotfoundComponent}
];

Open the studentlist.component.html file and replace it with the below code.

<div>
  <table border="1">
    <thead>
      <th>Id</th>
      <th>Name</th>
      <th>Age</th>
      <th>Gender</th>
      <th>Pass Params</th>      
    </thead>
    <tr *ngFor="let student of studentList">
      <td>{{student.id}}</td>
      <td>{{student.name}}</td>
      <td>{{student.age}}</td>
      <td>{{student.gender}}</td>     
      <td><span><a routerLink="/studentlist/editstudent">Edit</a></span></td>
    </tr>
  </table>
</div>
<div><router-outlet></router-outlet></div>

In the above snippet the <router-outlet></router-outlet> loads the child components of 'studentlist' component. Here it loads the 'editstudent' component. You can check it by clicking the edit link in the student list table.

Pass parameters in URL and get parameters from URL in Angular Application

Here let us see, pass the parameters in URL by using routerLink directive and getting the parameters from URL by using ActivatedRoute service.

We already created the EditstudentComponent as a child-level component of StudentlistComponent. In that component, we pass the parameters of student id like below.

Do the changes in the below files

studentlist.component.html

<td><span><a routerLink="/studentlist/editstudent/{{student.id}}">Edit</a></span></td>

app-routing.module.ts

{path:'studentlist', component:StudentlistComponent, children:[{path:'editstudent/:id', component:EditstudentComponent}]},

path:'editstudent/:id' is equivalent to the URL 'http://localhost:4200/studentlist/editstudent/id'

Now save all the changes and run the application again then click the edit link in the student list page and you can see the student id passed as a parameter in the URL.

We can pass the parameters with URL in different ways by using the routerLink directive.

routerLink="/studentlist/editstudent/{{student.id}}"
(or)
[routerLink]="['/studentlist/editstudent',student.id]"

Get Parameters from URL

We can get the parameters from the URL by using the ActivatedRoute service. Usually angular adds all the parameters to the map called ParamMap. We can retrieve the parameters from the map by using the get or getAll methods of the map.

There are two ways to retrieve the parameters from the URL.

  1. Snapshot .
  2. Observable.

Let us take the EditstudentComponent to use both the Snapshot and Observable methods.

We have to import the ActivatedRoute service and get the parameters in the ngOnInit function.

editstudent.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-editstudent',
  templateUrl: './editstudent.component.html',
  styleUrls: ['./editstudent.component.css']
})
export class EditstudentComponent implements OnInit {
  studentId:any
  constructor(private activatedroute:ActivatedRoute) { }
  ngOnInit(): void {
    this.studentId=this.activatedroute.snapshot.paramMap.get("id");  
  }
}

editstudent.component.html

<h1>Edit Student Page (Child page of Student List)</h1>
<p>Student Id is {{studentId}} (gettting from url param)</p>

Now save all the changes and run the application again. Click the Edit link from the student list table and you can see the edit student page that displays the corresponding student id.

Note: If you click the Edit link of every student one by one then you can see the URL updated with the corresponding student id. But on the page, the updated id will not be displayed. Because the edit student page is the child page of the student list page so the Snapshot method doesn't get the latest parameter.

To overcome this, we have to use the Observable method to retrieve the parameters. This method gets the latest parameter from the URL.

Using Observable to get the parameter from the URL

The below code retrieves the latest id of the student from the URL by subscribing to the observable property.

editstudent.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-editstudent',
  templateUrl: './editstudent.component.html',
  styleUrls: ['./editstudent.component.css']
})
export class EditstudentComponent implements OnInit {
  studentId:any
  constructor(private activatedroute:ActivatedRoute) { }
  ngOnInit(): void { 
    this.activatedroute.paramMap.subscribe(params => { 
    this.studentId = params.get('id'); 
  });
  }
}

Use Relative Paths and Relative Routes in Angular Application

Relative Paths

We can use the relative path directly in the routerLink directive. In the above example if we want to move the subjects list page from the edit student page then we have to write the relative path like below.

editstudent.component.html

<h1>Edit Student Page (Child page of Student List)</h1>
<p>Student Id is {{studentId}} (gettting from url param)</p>

<div>Relative Path Example</div>
<a routerLink="../../../subjects" >Go to Subjects List</a>

Now if you click the link 'Go to Subjects List' then it will move to the subjects list page. Here the relative path is routerLink="../../../subjects"

Relative Routes

If you want to specify a relative route then you have to use NavigationExtras and relativeTo property from the angular router service @angular/router.

The example below specifies the relative route in SubjectsComponent.

subjects.component.html

<div>
    <table border="1">
      <thead>
        <th>Id</th>
        <th>Subject Name</th>          
      </thead>
      <tr *ngFor="let subject of subjectList">
        <td>{{subject.id}}</td>
        <td>{{subject.name}}</td>        
      </tr>
    </table>
  </div>
<div>Relative Route Example</div>
<button (click)="goToStudentList()">Go to Students List Page</button>

subjects.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentserviceService } from '../studentservice.service';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
  selector: 'app-subjects',
  templateUrl: './subjects.component.html',
  styleUrls: ['./subjects.component.css']
})
export class SubjectsComponent implements OnInit {
  subjectList:any;
  constructor(private studentService: StudentserviceService,private router:Router, private route:ActivatedRoute) { }
  ngOnInit(): void {
    this.subjectList = this.studentService.getSubjectList();
  }
  goToStudentList(){
    this.router.navigate(['../studentlist'], { relativeTo: this.route });
  }
}

In the above example the Relative Route specified within the method goToStudentList(). If you click the button 'Go to Students List Page' then it will move to the student list page that is relative to the current path.

Hope you understood the routing concepts of angular application. Thanks!. Keep Reading!.

Download the full source code from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *