How to go back to last page in angular

How to go back to last page in angular

In this article lets understand how to go back to last page in angular.

In Angular, you can navigate back to the previous page using the Location service or the Router service. Here’s how you can implement both approaches:

Using the Location service:

Import the Location service from the @angular/common module in your component:

import { Location } from '@angular/common';

Inject the Location service in your component’s constructor:

constructor(private location: Location) { }

Call the back() method of the Location service to navigate back to the previous page:

goBack() {
  this.location.back();
}

In your template, bind the goBack() method to a button or a link to trigger the navigation:

<button (click)="goBack()">Go Back</button>

This approach uses the browser’s history to navigate back to the previous page.

Using the Router service:

Import the Router service from the @angular/router module in your component:

import { Router } from '@angular/router';

Inject the Router service in your component’s constructor:

constructor(private router: Router) { }

Call the navigateBack() method of the Router service to navigate back to the previous page:

goBack() {
  this.router.navigate(['/']); // Provide the route path or specify the route as needed
}

In your template, bind the goBack() method to a button or a link to trigger the navigation:

<button (click)="goBack()">Go Back</button>
  1. This approach allows you to navigate to a specific route or a defined path by providing the appropriate route path in the navigate() method.

Choose the approach that best fits your use case. Both methods provide a way to navigate back to the previous page in your Angular application.

Read more on angular here.