How do I navigate to a parent route from a child route?
Solution 1
Do you want a link/HTML or do you want to route imperatively/in code?
Link: 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 ../../parent;abc=xyz
[routerLink]="['../../parent', {abc: 'xyz'}]"
// with query param and fragment ../../parent?p1=value1&p2=v2#frag
[routerLink]="['../../parent']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"
With RouterLink, remember to import and use the directives
array:
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
directives: [ROUTER_DIRECTIVES],
Imperative: The navigate()
method requires a starting point (i.e., the relativeTo
parameter). If none is provided, the navigation is absolute:
import { Router, ActivatedRoute } from '@angular/router';
...
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 ../../parent;abc=xyz
this.router.navigate(["../../parent", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment ../../parent?p1=value1&p2=v2#frag
this.router.navigate(["../../parent"], {relativeTo: this.route,
queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});
// navigate without updating the URL
this.router.navigate(["../../parent"], {relativeTo: this.route, skipLocationChange: true});
Solution 2
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';
Solution 3
You can navigate to your parent root like this
this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });
You will need to inject the current active Route in the constructor
constructor(
private router: Router,
private activeRoute: ActivatedRoute) {
}
Solution 4
constructor(private router: Router) {}
navigateOnParent() {
this.router.navigate(['../some-path-on-parent']);
}
The router supports
- absolute paths
/xxx
- started on the router of the root component - relative paths
xxx
- started on the router of the current component - relative paths
../xxx
- started on the parent router of the current component
Solution 5
without much ado:
this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
parameter '..' makes navigation one level up, i.e. parent :)
Related videos on Youtube
Carl Boisvert
Updated on July 08, 2022Comments
-
Carl Boisvert almost 2 years
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 the admin application.My problem is that I can't use the
global navigation menu
because the router tries to route in myAdminComponent
instead of myAppCompoment
. So my navigation is broken.Another problem is that if someone want to access the URL directly, I want to redirect to the parent "login" route. But I can't make it work. It seems to me like theses two issues are similar.
Any idea how it can be done?
-
Jiang YD about 8 yearsplease add some code
-
Junaid over 2 yearsAs pointed out by others, please add some code or the basic routes config so that your question can attract more precise answers.
-
-
Toby Speight about 8 yearsAlthough this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.
-
Günter Zöchbauer about 8 years@TobySpeight Fair enough. I assumed
../
is known well enough, but in the end it's still ambiguous. Thanks for the hint. -
Carl Boisvert about 8 yearsThanks for the answer, I've been working on this website for quite some time, so Angular as obviously been updated since. I've try this solution in my current version and it doesn't work. Let me update and I'll comment back after.
-
Tomato over 7 yearsthe
router.navigate(string)
method doesn't seem to exist in the current version of Angular (2.2). I searched in the docs and only foundnavigate(commands: any[], extras?: NavigationExtras) : Promise<boolean>
. Or am I totally missing something? -
leviathanbadger about 7 yearsThis only works if you were in the parent route previously. Parent routes have nothing to do with the browser history...
-
gye almost 7 years@Tomato, you need to put [] around the routes. For example, this.router.navigate(["../../parent"], {relativeTo: this.route});
-
Andrew Andreev almost 7 yearsit navigates back, but doesn't navigate to parent of component
-
redfox05 over 6 yearshow do you pass the
relativeTo
data when you are using [routerLink] in the html instead of typescript? -
isherwood about 6 yearsRather than a date it would be more useful to mention the Angular version you happen to be using.
-
ne1410s about 6 years@isherwood I agree. Apologies. If I remember correctly, I wrote it for Angular 4.0.x and it was still functional in 4.3.x. Unfortunately I have moved away from Angular now,
-
DesTroy over 5 yearsweirdly, this always returns an empty array, and achieves the same result as
this._router.navigate([])
, whilethis._router.navigate([[]])
takes to the parent route, if and only if the parent route isn't root itself. -
Sagar Zala over 5 yearsAdding some explanation would make this answer more useful.
-
Ian Samz over 5 years@ne1410s Thanks alot was missing the relative :this.route
-
T04435 over 5 yearsThis shouldn't be used, if the user goes to the component from an external site, it would be taken back to that site. This code is the same as clicking the BACK BUTTON IN THE BROWSER
-
Don Thomas Boyle over 5 yearsNote: Will NOT work with additional router segments on lazy loaded modules. EX:
parentPath
: 'work:queue' (which has children) and said children load child module with parameters.fullCurrentPath
: 'work/shipping/module/list'. The above code can't loadparentPath
fromfullCurrentPath
. -
Don Thomas Boyle over 5 yearsupdated code to reflect Angular 6 changes and proper parent finding with parent and child containing children in routes.
-
kayjtea over 5 yearsAre you sure this isn't something specific to your use case? It would seem not appending the last path would turn ['orders', '123', 'items', 1] into just ['orders'], which doesn't seem right at all. In any case, we just went from Angular 5 to 7 and didn't touch this coded.
-
Terry Lam over 5 yearsMany people suggest navigate to sibling by this.router.navigate(["../sibling"], {relativeTo: this.route}); However, this is not working anymore. I found this answer work probably. Instead of using '../' to navigate to parent. change relativeTo from this.route to this.route.parent is the correct way
-
Chris Lamothe over 5 years@TerryLam: Works great for me. ng7 are you certain you are calling this from inside a component or a service provided in your component
-
Terry Lam over 5 years@ChrisLamothe: Oh yes I made a mistake. It works in general case. However, it doesn't work in auxiliary routes. That means this.router.navigate(['../sibling']) is working but not this.router.navigate([{outlets: {'secondary': ['../sibling']}}]). In auxiliary routing, I have to use this.router.navigate([{outlets: {'secondary': ['sibling']}}], {relativeTo:this.activatedRoute.parent}).
-
Roganik about 5 yearsAlso, the navigation method from this answer
this.router.navigate(['.'], {relativeTo: this.activeRoute.parent});
will work correctly in a case, when you use the same component in two paths: /users/create and /users/edit/123. In both cases it'll navigate to parent /users. The regular navigation withthis.router.navigate([".."], {relativeTo: this.activeRoute})
will work only for the users/create but it won't work for the users/edit/123 because it'll navigate to not-existing /users/edit/ route. -
Konrad Viltersten over 4 yearsI don't get your code to work as expected. However, by adding explicitly , { relativeTo: this.route } as a second parameter in the call to navigate, it works. I'd chalk it up to a stupid typo if it hadn't been for the fact that your answers generally have an extreme degree of accuracy. Is it perhaps a change in behavior of the router since the answer was provided (3.6 years ago, which in Angular years is like a half'ish eternity)?
-
Konrad Viltersten over 4 years+1 for an alternative but personally, I'm a bit of a byte chaser and would invest an extra dot in the parameter, [".."], to eliminate reference to parent, { relativeTo: this.route }.
-
Konrad Viltersten over 4 yearsYou might want to mention the purpose/need of skipLocationChange.
-
Günter Zöchbauer over 4 yearsThis is an old answer and the router changed a lot at this time. I think my answer is just outdated considering that there are several answers with more upvotes. I'm not doing that much web UI stuff anymore and don't have all details on the top of my head.
-
Mateo Tibaquira over 4 yearsawesome, thanks! I'm used to have empty Route full of children, so I needed to navigate
relativeTo: this.route.parent.parent
thanks again! -
oCcSking over 4 yearsthe same with services?
-
Vrajendra Singh Mandloi almost 4 yearstheir are number of div on my page.. on click of every div i pass query parms and load a component. now using browser back button i want to go back how to do that?
-
nelson6e65 over 3 yearsFor some reason, in my case I have to use
../../../
instead of../
to navigate to parent ('/users'
from'/users/1'
). -
Gerald Zehetner over 3 yearsPlease update your answer with some descriton why this works. Please see the How to Answer.
-
Cafn over 3 yearsIn addition to the previous comment, add a reference to what does the "this.activeRoute" is related to
-
Simon Hansen almost 3 yearssomething good to know is, that router and activatedRoute need to be injected in the component itself, this can not be wrapped into a extra service and a method like
goUp
.