Leandro Lima
Leandro Lima

Reputation: 1164

Angular 5 navigate

Considering I'm on route

/parentOne/param1/param2/child

Is there any way for me to navigate to this another route, without passing the entire path (/param1/param2/child)?

/parentTwo/param1/param2/child

The solution I have today:

const path = this.router.url.replace(regex, 'parentTwo');
this.router.navigate([path]);

The solution I wish I could implement:

this.router.navigate(['parentTwo', '...']);

Upvotes: 5

Views: 357

Answers (2)

xdeepakv
xdeepakv

Reputation: 8135

Check out NavigationExtras. https://angular.io/api/router/NavigationExtras Using relativeTo and relative path, you can navigate

 go() {
    this.router.navigate(['../list'], { relativeTo: this.route });
  }

Example:

const appRoutes = [
  {
    path: 'p1', component: P1,
    children: [
      {
        path: ':id',
        component: P1C
      }
    ]
  },
  {
    path: 'p2', component: P2,
    children: [
      {
        path: ':id',
        component: P2C
      }
    ]
  },
];

this.r.navigate(['../../p1', '2'], {relativeTo: this.a})

Upvotes: 1

ForestG
ForestG

Reputation: 18123

You can get the current url in a component like this for instance:

constructor(route: ActivatedRoute; router: Router) {      
   const url: Observable<string> = route.url;
  }
}

You can then use this.router.navigate(url) to navigate to specific url.

Upvotes: 0

Related Questions