How do I navigate to a parent route from a child route?

132,046

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 :)

Share:
132,046

Related videos on Youtube

Carl Boisvert
Author by

Carl Boisvert

Updated on July 08, 2022

Comments

  • Carl Boisvert
    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 my AdminComponent instead of my AppCompoment. 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
      Jiang YD about 8 years
      please add some code
    • Junaid
      Junaid over 2 years
      As pointed out by others, please add some code or the basic routes config so that your question can attract more precise answers.
  • Toby Speight
    Toby Speight about 8 years
    Although 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
    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
    Carl Boisvert about 8 years
    Thanks 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
    Tomato over 7 years
    the router.navigate(string) method doesn't seem to exist in the current version of Angular (2.2). I searched in the docs and only found navigate(commands: any[], extras?: NavigationExtras) : Promise<boolean>. Or am I totally missing something?
  • leviathanbadger
    leviathanbadger about 7 years
    This only works if you were in the parent route previously. Parent routes have nothing to do with the browser history...
  • gye
    gye almost 7 years
    @Tomato, you need to put [] around the routes. For example, this.router.navigate(["../../parent"], {relativeTo: this.route});
  • Andrew Andreev
    Andrew Andreev almost 7 years
    it navigates back, but doesn't navigate to parent of component
  • redfox05
    redfox05 over 6 years
    how do you pass the relativeTo data when you are using [routerLink] in the html instead of typescript?
  • isherwood
    isherwood about 6 years
    Rather than a date it would be more useful to mention the Angular version you happen to be using.
  • ne1410s
    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
    DesTroy over 5 years
    weirdly, this always returns an empty array, and achieves the same result as this._router.navigate([]), while this._router.navigate([[]]) takes to the parent route, if and only if the parent route isn't root itself.
  • Sagar Zala
    Sagar Zala over 5 years
    Adding some explanation would make this answer more useful.
  • Ian Samz
    Ian Samz over 5 years
    @ne1410s Thanks alot was missing the relative :this.route
  • T04435
    T04435 over 5 years
    This 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
    Don Thomas Boyle over 5 years
    Note: 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 load parentPath from fullCurrentPath.
  • Don Thomas Boyle
    Don Thomas Boyle over 5 years
    updated code to reflect Angular 6 changes and proper parent finding with parent and child containing children in routes.
  • kayjtea
    kayjtea over 5 years
    Are 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
    Terry Lam over 5 years
    Many 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
    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
    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
    Roganik about 5 years
    Also, 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 with this.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
    Konrad Viltersten over 4 years
    I 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
    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
    Konrad Viltersten over 4 years
    You might want to mention the purpose/need of skipLocationChange.
  • Günter Zöchbauer
    Günter Zöchbauer over 4 years
    This 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
    Mateo Tibaquira over 4 years
    awesome, thanks! I'm used to have empty Route full of children, so I needed to navigate relativeTo: this.route.parent.parent thanks again!
  • oCcSking
    oCcSking over 4 years
    the same with services?
  • Vrajendra Singh Mandloi
    Vrajendra Singh Mandloi almost 4 years
    their 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
    nelson6e65 over 3 years
    For some reason, in my case I have to use ../../../ instead of ../ to navigate to parent ('/users' from '/users/1').
  • Gerald Zehetner
    Gerald Zehetner over 3 years
    Please update your answer with some descriton why this works. Please see the How to Answer.
  • Cafn
    Cafn over 3 years
    In addition to the previous comment, add a reference to what does the "this.activeRoute" is related to
  • Simon Hansen
    Simon Hansen almost 3 years
    something 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.