0

I have the below routes:

export const appRoutes: Routes = [
  {
    path: '',
    data: { breadcrumb: 'Parent' , rootRoute : true },
    children: [
      {
        path:'', component: ComponentA,
        pathMatch: 'full',
      },
      {
        path:'details/:id', component: ComponentDetails,
        pathMatch: 'full',
        data: { breadcrumb: 'Details Page' , rootRoute : false },
      },
    ]
  }
];

When I go deeper into nested child routes and lets say, I want to go back to my parent using a custom defined back-button in my app, for which I need to determine the parent route( not previous route) when I'm at a child route. How can this be achieved?

What I have tried?

Angular 2 get parent activated route

Angular version : 12.x

codaholic
  • 315
  • 1
  • 12

3 Answers3

0

In the output of activatedroute, there is a key called _routerstate.

You might want to check _routerstate -> snapshot -> url.

This is the whole url. You can split this string and get the first string as the parent route.

vsnikhilvs
  • 456
  • 1
  • 3
  • 10
  • Yes I did come across this, but is there no way to get the parent route itself without this hack? Reason being: parent route: app/component/A child : app/component/A/details/1 where lets say 1 is the ID of the component. Now this route logic is going to be generic. so it should be able to determine the parent route in any case whatsoever. which might be risky if i implement a logic as such, hence i wanted to find a way to get the parent logic itself – codaholic Aug 09 '21 at 15:46
  • Came across this. Please check if you can find anything here. https://stackoverflow.com/questions/46722761/how-to-check-active-child-router-from-parent-router-or-parent-router-against – vsnikhilvs Aug 10 '21 at 03:45
0

Provides the complete route as @vsnikhilvs suggested.

this.currentRouteString = this.route && this.route['_routerState'] && this.route['_routerState']['snapshot'] && this.route['_routerState']['snapshot']?.url;

The below provides the child path, here 'details':

this.currentRoutePath = this.route?.url['_value'] && Array.isArray(this.route?.url['_value']) && this.route?.url['_value'].length>0 && this.route?.url['_value'][0]?.path;

Spitting this as below works:

this.currentRouteString.split(this.currentRoutePath)[0]

codaholic
  • 315
  • 1
  • 12
0

this.route.parent.url

then subscribe to the observable and access: url[0].path

I am using angular 15 though not sure if it's on 12