How do I navigate to a sibling route?
Asked Answered
B

4

74

Let's presume I got this router config

export const EmployeeRoutes = [
   { path: 'sales', component: SalesComponent },
   { path: 'contacts', component: ContactsComponent }
];

and have navigated to the SalesComponent via this URL

/department/7/employees/45/sales

Now I'd like to go to contacts, but as I don't have all the parameters for an absolute route (e.g. the department ID, 7 in the above example) I'd prefer to get there using a relative link, e.g.

[routerLink]="['../contacts']"

or

this.router.navigate('../contacts')

which unfortunately doesn't work. There may be an obvious solution but I'm not seeing it. Can anyone help out here please?

Barbera answered 28/7, 2016 at 10:51 Comment(0)
H
126

If you are using the new router (3.0.0-beta2), you can use the ActivatedRoute to navigate to relative path as follow:

constructor(private router: Router, private r:ActivatedRoute) {} 

///
// DOES NOT WORK SEE UPDATE
goToContact() {
  this.router.navigate(["../contacts"], { relativeTo: this.r });
}

Update 08/02/2019 Angular 7.1.0

current route: /department/7/employees/45/sales

the old version will do: /department/7/employees/45/sales/contacts

As per @KCarnaille's comment the above does not work with the latest Router. The new way is to add .parent to this.r so

    // Working(08/02/2019) 
    // DOES NOT WORK SEE UPDATE
    goToContact() {
       this.router.navigate(["../contacts"], { relativeTo: this.r.parent });
    }

the update will do: /department/7/employees/45/contacts

Update 12/12/2021 Angular > 10

As @ziz194 mention it, this is how it now works.

constructor(private router: Router, private r:ActivatedRoute) {} 

goToContact() {
  this.router.navigate(["contacts"], { relativeTo: this.r });
}
Houdon answered 28/7, 2016 at 11:0 Comment(7)
I'm actually in the same situation, but it doesn't work for me... something has changed since the official release ?Brietta
@Brietta Hmm I'm on @angular/router 3.0.0 (finished, not beta) and it's still working properly. Not sure if they have any breaking changes since then.Houdon
@Harry Ninh It was my fault actually. A simple issue with path structure :) It's workingBrietta
How can we do that from html with routerLink ?Melt
This actually shouldn't be solved by .parent just remove the ../ and keep just "contacts" in the path, like this: this.router.navigate(["contacts"], { relativeTo: this.r});Tolkan
This is good info. Shame angular don't include USEFUL information like this in their docs, like all will every need is a heroes app. How complex can you make routing? You have a tree, absolute and relative paths, arrgh.Fishy
I really dont understand this logic. So RELATIVE to the parent route, we navigate back one level (grandparent), and move forward to contacts. This should give us /department/7/employees/contactsMichale
H
91

The RouterLink directive always treats the provided link as a delta to the current URL:

[routerLink]="['/absolute']"
[routerLink]="['../../parent']"
[routerLink]="['../sibling']"
[routerLink]="['./child']"     // or
[routerLink]="['child']" 

// with route param     ../sibling;abc=xyz
[routerLink]="['../sibling', {abc: 'xyz'}]"
// with query param and fragment   ../sibling?p1=value1&p2=v2#frag
[routerLink]="['../sibling']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"

The navigate() method requires a starting point (i.e., the relativeTo parameter). If none is provided, the navigation is absolute:

constructor(private router: Router, private route: ActivatedRoute) {}

this.router.navigate(["/absolute/path"]);
this.router.navigate(["../../parent"], {relativeTo: this.route});
this.router.navigate(["../sibling"],   {relativeTo: this.route});
this.router.navigate(["./child"],      {relativeTo: this.route}); // or
this.router.navigate(["child"],        {relativeTo: this.route});

// with route param     ../sibling;abc=xyz
this.router.navigate(["../sibling", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment   ../sibling?p1=value1&p2=v2#frag
this.router.navigate(["../sibling"], {relativeTo: this.route, 
    queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});

// RC.5+: navigate without updating the URL 
this.router.navigate(["../sibling"], {relativeTo: this.route, skipLocationChange: true});
Hummer answered 6/8, 2016 at 19:41 Comment(9)
Why does navigate behave differently?Guizot
do you have a working example of the [routerLink] directive working with sibling route? It keeps switching to an absolute route for me if I use [routerLink]="['../sibling']"Pelias
router.navigate() requires the first argument to be an array - but none of these work even as an arrayTalented
@Jonathan002, same for me. Did you find anything that works?Kubis
This answer isn't completely accurate. A path ../something is relativeTo where the component is rendered in the router tree, but it is not relative to the current route because that could be a route deeper in the route tree from where the [routerLink] was applied. If you're trying to do a breadcrumb as an example in the header of your page. It will be relative to where that header is rendered, and most likely not what you want.Ozonize
@Ozonize Then what's the best way to do breadcrumbs? Use router.createUrlLink to create an absolute link based on the currentRoute somewhere and use that inside the router link?Mcculley
@Botis I updated my breadcrumbs by listening for changes to router.events and NavigationEnd, then I recursive walk router.routerState.snapshot.root and rebuild the breadcrumb trail from there. I check for data attached to route children to see if I should create a breadcrumb for that route, and then I convert activatedRouteSnapshot.pathFromRoot into a string as the URL for that crumb. Yes, it's very complicated. Sadly, couldn't find a better way.Ozonize
@Ozonize the answer is in fact accurate. "../something" is a relative path, it will be relative to something. In the case of the [routerLink] directive, if [relativeTo] is not specified, it will be relative to the activated route of the host scope (which has always been the intended behavior). Paths in a breadcrumb should always be absolute.Schargel
"The RouterLink directive always treats the provided link as a delta to the current URL" - That's not true. It's relative to the activated route of the component you are in, which is either the current url or a subset of it. (it it has more active children.)Sentiment
P
0

I tried the following and it worked:

this.router.navigate(["contacts"], { relativeTo: this.r.parent });

Poodle answered 23/12, 2022 at 10:33 Comment(0)
A
0

For some reason, possibly related to multiple outlet I'm having in the same view, I either had to target this.activatedRoute.parent.parent (very inconvenient) or to target the current view and use the double dot path.

    this.router.navigate(['..', "contacts"], { relativeTo: this.activatedRoute });
Aframe answered 8/2, 2023 at 13:23 Comment(1)
Thanks man, this is so frustrating... it turns out that the '..' doesn't even work. this.activatedRoute.parent worked for me. (Angular 14) Documentation is sh#tKochi

© 2022 - 2024 — McMap. All rights reserved.