My problem is quite classic. I have a private part of an application which is behind a login form
. When the login is successful, it goes to a child route for th
Another way could be like this
this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL
and here is the constructor
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
My routes have a pattern like this:
When i am on Edit page, for example, and i need go back to list page, i will return 2 levels up on the route.
Thinking about that, i created my method with a "level" parameter.
goBack(level: number = 1) {
let commands = '../';
this.router.navigate([commands.repeat(level)], { relativeTo: this.route });
}
So, to go from edit to list i call the method like that:
this.goBack(2);
without much ado:
this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
parameter '..' makes navigation one level up, i.e. parent :)
My solution is:
const urlSplit = this._router.url.split('/');
this._router.navigate([urlSplit.splice(0, urlSplit.length - 1).join('/')], { relativeTo: this._route.parent });
And the Router
injection:
private readonly _router: Router
This seems to work for me as of Spring 2017:
goBack(): void {
this.router.navigate(['../'], { relativeTo: this.route });
}
Where your component ctor accepts ActivatedRoute
and Router
, imported as follows:
import { ActivatedRoute, Router } from '@angular/router';
To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19
let routerLink = this._aRoute.parent.snapshot.pathFromRoot
.map((s) => s.url)
.reduce((a, e) => {
//Do NOT add last path!
if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
return a.concat(e);
}
return a;
})
.map((s) => s.path);
this._router.navigate(routerLink);
This has the added bonus of being an absolute route you can use with the singleton Router.
(Angular 4+ for sure, probably Angular 2 too.)