Hongbo Miao
Hongbo Miao

Reputation: 49984

How to go back to last page when having child router?

How to go back to last page when having child router?

Please see comments in code for details. Thanks

export class OneProductComponent {
  prevUrlPath:string = '';

  constructor(private _router: Router) {}

  routerOnActivate(next:ComponentInstruction, prev:ComponentInstruction) {
    this.prevUrlPath = prev.urlPath;
  }

  goBack() {
    // I have to manually add "products/" here, but if I need 
    // go back to root home page. Then I shouldn't add "products/" here.
    // Is there a smart way to to this?
    this._router.navigateByUrl(`products/${this.prevUrlPath}`);
  }
}

Upvotes: 2

Views: 5685

Answers (3)

Rojin Gharooni
Rojin Gharooni

Reputation: 69

try this in html tag

 routerLink="../LASTPAGE"

try routerLink="../LASTPAGE"

Upvotes: 1

Sean Aitken
Sean Aitken

Reputation: 1207

Latest docs for Angular 7.2.7 (inspired by @Victor's link) basically say to use the injected Location service to achieve the same thing. https://angular.io/tutorial/toh-pt5#find-the-way-back

(Copied from the sample)

In the template:

<button (click)="goBack()">go back</button>

And the component:

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

Upvotes: 0

Victor Martinez
Victor Martinez

Reputation: 1180

The angular 2 documentation on routing suggests that you use the window object instead https://angular.io/docs/ts/latest/tutorial/toh-pt5.html#!#find-our-way-back

goBack() {
  window.history.back();
}

Upvotes: 8

Related Questions