If you're looking for a stable, Angular-like approach to achieve this, here's one way you can do it:
import {ActivatedRoute, Router, UrlTree} from '@angular/router';
//...
constructor(private router: Router, private route: ActivatedRoute) {}
doSomethingWithParentRoute() {
// You can generate a UrlTree for the parent path like so:
const parentUrlTree: UrlTree = this.router.createUrlTree(['../'], { relativeTo: this._route });
// If you need to go up multiple levels, use something like '../../../'
// Now you can manipulate the urlTree as needed:
let path: string = this.router.serializeUrl(parentUrlTree);
// or
path = this.parentUrlTree.toString();
// and so on...
// Additionally, you can access the parent route as an ActivatedRoute object by:
const parentRoute: ActivatedRoute = this.route.parent;
}
IMPORTANT:
If you are using Angular version below 11, or have set relativeLinkResolution: 'legacy'
in your router module, then the '../'
refers to the same level in the path, so consider using '../../'
instead. More information available at: https://angular.io/guide/deprecations#relativeLinkResolution