Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Angular router navigate method

Suggested Videos
Part 34 - Angular singleton service | Text | Slides
Part 35 - Angular Injector | Text | Slides
Part 36 - Angular root injector | Text | Slides

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.


Angular router navigate method

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.

<div style="margin-top:5px">
    <input type="button" class="btn btn-primary" value="Back to Employees List"
           (click)="onBackButtonClick()"/>
</div>

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.

onBackButtonClick() :void {
    this._router.navigate(['/employees']);
}

Angular 2 tutorial for beginners

3 comments:

  1. Hi You changed completely the employee component as well as additions to the Employee Service. Where it is described?? Thx

    ReplyDelete
    Replies
    1. Hi sorry for the comment. You explained it wonderfully in lesson 31 which i SKIPPED.
      Thx

      Delete
  2. hi sir,
    good morning i like your video tutorials . i learn lot of thing from you.now i need your help how to use scss instead of css in angular 2. i need some sample videos

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.