Implement simple back navigation with angular router

Viewed 2816

I would like to implement a back button inside my header: It will move back from child to parent route!

Suppose I have the following nested routes: / => /bar => /bar/foo

Now if I add a 'Go-Back' button inside my Foo component I can simply do

 this.router.navigate([".."], { relativeTo: this.activatedRoute });

However, in my case the back-button is in the header (AppComponent) meaning that the above code doesn't work, I guess that ActivatedRoute points to /

Stackblitz

So, my question is, how can I navigate back (child to parent) without ActivatedRoute?

UPDATE: I'm still working on this solution, I have the feeling that it should work (but right now isn't):

 const activatedRoute = this.injector.get(ActivatedRoute);
 this.router.navigate(['..'], { relativeTo: activatedRoute });

Stacblitz

2 Answers

You should try the Location service

import { Component } from "@angular/core";
import { Location } from "@angular/common";

@Component({
  selector: "my-app",
  template: `
    <div class="container">
      <button (click)="goBack()">Go Back</button><br />
      <a routerLinkActive="active" routerLink="/bar">Bar</a>

      <router-outlet></router-outlet>
    </div>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(private location: Location) {}

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

use the global window api: window.history.back();

Related