Author avatar

Yallaling Goudar

Understanding the Purpose of Routing in Angular

Yallaling Goudar

  • Feb 4, 2020
  • 7 Min read
  • 27,156 Views
  • Feb 4, 2020
  • 7 Min read
  • 27,156 Views
Languages Frameworks and Tools
Angular

Introduction

Routing in Angular helps us navigate from one view to another as users perform tasks in web apps. In this guide you will learn about Angular router's primary features.

Overview of Angular Routing

Some examples of actions users take while navigating in an app include:

  • Entering a URL in the address bar and the browser navigates to a corresponding page
  • Clicking links on the page and the browser navigates to a new page
  • Clicking the browser's back and forward buttons and the browser navigates backward and forward through the history of pages

Angular router can interpret a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that help it decide what specific content to present. You can bind the router to links on a page, and it will navigate to the appropriate application view when the user clicks a link.

Router Concepts

The Angular router is in its own library package, @angular/router. Import what you need from it as you would from any other Angular package. It is an optional service that presents a particular component view for a given URL.

File name: app.module.ts

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

Configuring the Router

Let's look at how to configure an Angular router. The following example creates five route definitions, configures the router via the RouterModule.forRoot() method, and adds the result to theAppModule`'s imports array.

File name: app.module.ts

1const appRoutes: Routes = [
2  { path: 'company', component: CompanyComponent },
3  { path: 'employee/:id',      component: EmployeeDetailComponent },
4  {
5    path: 'employees',
6    component: EmployeeListComponent,
7    data: { title: 'Employees List' }
8  },
9  { path: '',
10    redirectTo: '/employees',
11    pathMatch: 'full'
12  },
13  { path: '**', component: PageNotFoundComponent }
14];
15
16@NgModule({
17  imports: [
18    RouterModule.forRoot(
19      appRoutes,
20      { enableTracing: true }
21    )
22  ],
23  ...
24})
25export class AppModule { }
typescript

Route Parameters

Parameters passed along with a URL are called route parameters. Generate an employee dashboard component using the following CLI command.

1import { Component, OnInit } from '@angular/core';
2import { Router } from '@angular/router';
3import { Employee } from '../emploee/employee';
4import { EmployeeService } from '../employee/employee.service';
5@Component({
6  selector: 'app-employeedashboard',
7  templateUrl: './employeedashboard.component.html',
8  styleUrls: ['./employeedashboard.component.css']
9})
10export class EmployeeDashboardComponent implements OnInit {
11  employees: Employee[] = [];
12  constructor(
13    private router: Router,
14    private employeeService: EmployeeService) { }
15  ngOnInit() {
16    this.employeeService.getEmployees()
17      .subscribe(employees => this.employees = employees.slice(1, 5));
18  }
19  gotoDetail(employee: Employee) {
20    this.router.navigate(['/employeedetail', employee.id]);
21  }
22}
typescript

Import the router class from @angular/router module . Inject it into the component class through a constructor . The this.router.navigate() method is used to navigate to a specific URL programmatically. The Navigate() method takes two arguments: the path to navigate and tthe route parameter value to pass. Here the path will be employeedetail/<employee_id>.

Accessing Route Parameters

To access route parameters, use the ActivatedRoute class. In the example below, we see that when a specific employee is clicked, it renders the EmployeeDetailComponent. When the employees link is clicked, it navigates to EmployeesComponent.

Filename: employee-detail.component.ts

1import { Component, OnInit, OnDestroy } from '@angular/core';
2import { ActivatedRoute, ParamMap } from '@angular/router';
3import { switchMap } from 'rxjs/operators';
4import { Observable } from 'rxjs';
5import { Employee } from '../employee/employee';
6import { EmployeeService } from '../employee/employee.service';
7@Component({
8  selector: 'app-employee-detail',
9  templateUrl: './employee-detail.component.html',
10  styleUrls: ['./employee-detail.component.css']
11})
12export class EmployeeDetailComponent implements OnInit, OnDestroy {
13  employee: Employee;
14  error: any;
15  sub: any;
16  constructor(private employeeService: EmployeeService, private route: ActivatedRoute) { }
17  ngOnInit() {
18
19    this.sub = this.route.paramMap.pipe(switchMap((params: ParamMap) =>
20      this.employeeService.getEmployee(+params.get('id')))).subscribe(employee => this.employee = employee);
21  }
22  ngOnDestroy() {
23    this.sub.unsubscribe();
24  }
25  goBack() {
26    window.history.back();
27  }
28}
typescript

Import the ActivatedRoute class to access route parameters . Inject the ActivatedRoute class into the component class through a constructor . The ActivatedRoute class has a paramMap observable method that holds the route parameters. It has the switchMap() method to process the route parameters. ParamMap has a get() method to fetch a specific parameter value .

Conclusion

In this guide, we have explored how to use routing in Angular. We have also seen how to use routing in an app using routerlink and routing parameters.

You can learn more about Angular in my guide Using the Async Pipe in Angular.