DEV Community

German Gonzalo Saracca
German Gonzalo Saracca

Posted on

Back Button Navigation - Angular

I will go straight to the point, in a web app where I work the need emerged to standardize the behavior of such a simple button to navigate backwards.
Not to navigate backwards in the hierarchy of routes, for example:
Products => Product Detail => Edit Product
but to navigate backwards in the navigation history that the user had done.

First we thought about the simple history.go(-1), but the problem is that we didn't want to exit the web app, suppose the user arrives at a particular page of my web app and clicks the back button, I would exit the web app; and we didn´t want that.

Searching the internet we realized that such a simple task was not, or at least without making the task too complex, so I'm going to share our solution, at least with Angular.
*I have removed all styles to simplify the example.

back-button.component.ts Our logic 👇

import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'back-button',
  templateUrl: './back-button.component.html',
  standalone: true,
})
export class BackButtonComponent {
  constructor(private _location: Location, private _router: Router) {}

  goBack() {
    if (window.history.state.navigationId === 1) {
      this._router.navigate(['/home']);
    } else {
      this._location.back();
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

In the goBack function, we are checking if the navigationId property inside window.history.state is 1, which means that we are where the user first arrived in our web app, so instead of navigating outside our app we redirect user to the dashboard, otherwise just go back once.
Important: This navigationId is something that Angular pushes to the native state of the history and keeps incrementing it on location changes. We are using Angular 15.

back-button.component.html Our simple html 👇

<button (click)="goBack()">
  Back
</button>
Enter fullscreen mode Exit fullscreen mode

To conclude, I think it is a simple solution using the help that Angular gives us to keep track in some way the count of navigations between routes in our application.

Top comments (3)

Collapse
 
randellbrianknight profile image
Randell Brian Knight

Nice post, German! Welcome to the DEV community 🎉

Collapse
 
geromegrignon profile image
Gérôme Grignon

Not allowing the user to move away from the application is a really poor user experience and a dark pattern.

Collapse
 
germansaracca profile image
German Gonzalo Saracca

I think you misunderstood or I was not clear maybe, you can exit the application and navigate backwards with the browser buttons (I didn´t modify that behaviour of course!), just not with the button that is inside the UI of our app.