Navigate Back to Previous Page in Angular

angular navigate back

There are primarily 2 ways to navigate back to previous page in Angular:

  1. Using router.navigate() from @angular/router
  2. Using location.back() from @angular/common

We will learn about these 2 methods in a little more detail below.

Using router.navigate() to navigate back to previous page

We can use router.navigate with the whole path to go to the previous page, or we can also use relative routing.

Lets consider we are in a user context, where the url is something like /users/123 where 123 is the userID, and the user wants to go back to the /users/ page. So we can implement this using the angular’s router package

import { Router } from '@angular/router'

@Component({
  ...
})
export class UserDetailComponent {
  constructor(private router: Router) {}
  
  goBackToPrevPage(): void {
    this.router.navigate('/users');
  }
}

Using location.back() to navigate back to previous page

This works similar to the browser’s back button.

Location is provided by @angular/common to mimic the browser’s history manager.

import { Location } from '@angular/common'

@Component({
  ...
})
export class UserDetailComponent {
  constructor(private location: Location) {}

  goBackToPrevPage(): void {
    this.location.back();
  }
}

Note: This won’t work properly is the user has directly landed on this page. So need to add some logic to handle this situation too.

For learning more on Angular Routing, check out this article.

Leave a Reply

Your email address will not be published.