Need to take a user back to the previous route in your Angualr app? I'll show you how to do it here.

The scenario you're thinking of probably goes something like this: the user is viewing a page in your Angular app. There's a link or button on the page appropriately labeled "Back." When the user clicks that link or button, the application takes the user back to the previous page, whatever that was.

If that's what you're looking for (or something similar to it), read on.

Location, Location, Location

It's all about Location.

That's not just true in real estate. It's also true here.

That's because you'll use the Location service to take the user back to the previous route.

And like most services in Angular, you'll need to inject it via your constructor:

  constructor(private location: Location) { }

However, before you do that, make sure you got the right Location.

At the top of your code, where you've got all your imports, include this line:

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

Fail to do that and you'll likely end up with the wrong Location. Your IDE might not help you out in this situation, either. You'll probably have to add that line manually.

The back() Method

Now that you've got the Location service injected into your component, it's just a simple matter of invoking the back() method on it. That will take the user back to the previous route.

You can try a quick and dirty test as follows:

  ngOnInit(): void {

Now when the user navigates to the route associated with this component, the application will take him or her back to the previous route.

Since that's a fairly user-hostile thing to do, you'll want to delete that line immediately and test it out some other way.

One way you can do that is by adding a button in the template:

<button (click)="back()">Back</button>

And then add a back() method in the component like this:

  ngOnInit(): void {

That should do the trick.

Wrapping It Up

That's it. That's how you take the user back to a previous route from the current location.

Now it's up to you to take what you've learned here and make it your own.

Have fun!

Photo by NEOSiAM 2021 from Pexels