How to Navigate to Previous Page in Angular

In Applications, Sometimes we like to offer users a way to navigate back to where they had been before.

Let's explore this

In a example, if you have a list of products linked to a detail view and you want to display some kind of back button to return to the product list. 

Static Back Navigation Routing

Let's assume we are on product detail page. and wants to go back on product llist page.

<a routerLink="/products">Back to the product list from product detail page</a> // in html file

We can also do same thing from component file.


import { Router } from '@angular/router'

@Component({...})
export class ProductDetailComponent {
  constructor(private router: Router) {}

  back(): void {
    this.router.navigate('/products');
  }
}

Dynamic Back Navigation Routing


import { Location } from '@angular/common'
import { Router, NavigationEnd } from '@angular/router'

@Component({...})
export class ProductDetailComponent {
  private urlHistory: string[] = []

  constructor(private location: Location, private router: Router) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.urlHistory.push(event.urlAfterRedirects)
      }
    })
  }

  back(): void {
    this.urlHistory.pop()
    if (this.urlHistory.length > 0) {
      this.location.back()
    } else {
      this.router.navigateByUrl('/')
    }
  }
}

 

Hope this help you, please do let us know your reviews or suggestions to make it more better if you have :)

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone