Angular router navigate method

In this video we will discuss the use of Angular Router service navigate() method. This method is useful when you want to navigate to another page programmatically.

Let us understand this with an example. Here is what we want to do. On the EmployeeComponent that displays specific employee details, we want to include a Button as shown in the image below. When we click the button we want to redirect the user to EmployeeListComponent.

Step 1 : Include the following HTML markup for the button on employee.component.html. Notice we are using Bootstrap button css classes (btn & btn-primary) to style the button. We are using event binding to bind click event of the button to bind to "onBackButtonClick()" method in the EmployeeComponent class.

Step 2 : In the EmployeeComponent class ie. in employee.component.ts file make the following changes

Inclue the following Import statement to import Router service from '@angular/router'import { Router } from '@angular/router';

Specify a dependency on the Router service using the EmployeeComponent class constructor. The angular injector will automatically inject an instance of the Router service when an instance of EmployeeComponent is created.constructor(private _router: Router) {}

Finally include, "onBackButtonClick()" method. Notice we are using the Router service navigate() method to navigate to "/employees" route. This route is already defined in the root module (app.module.ts) which redirects the user to EmployeeListComponent.