Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate relative with Angular 2 Router (Version 3)

How to navigate relative from /questions/123/step1 to /questions/123/step2 within a component using Router without string concatenation and specifying /questions/123/?

I've added an own answer below. Please feel free to suggest a better answer. ;-) I guess there are better approaches.

like image 260
Thomas Avatar asked Aug 24 '16 13:08

Thomas


3 Answers

After doing some more research I came across with

this.router.createUrlTree(['../step2'], {relativeTo: this.activatedRoute});

and

this.router.navigate(['../step2'], {relativeTo: this.activatedRoute});

First approach (Router.createUrlTree API) did not work for me, i.e. nothing happened. Second approach (Router.navigate API) works.

Update 2016-10-12

There is another stackoverflow question as well:

  • How do I navigate to a sibling route

Update 2016-10-24

Documentation:

  • Routing & Navigation (Relative Navigation)

Update 2019-03-08

It seems that there were changes in Angular 7.1. There is an answer in another post how to solve it with Angular 7.1. Please refer to https://stackoverflow.com/a/38634440/42659.

like image 126
Thomas Avatar answered Nov 14 '22 07:11

Thomas


First, inject router & ActivatedRoute on constructor

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

then use to Click Event:

onEditClick(){
        this.router.navigate(['edit'],{relativeTo:this.route});

You navigate to the expected page.In my scenario, I wanted to go recipe /1 to edit the recipe. http://localhost:4200/recipes/1/edit

like image 43
Shahin Al Kabir Mitul Avatar answered Nov 14 '22 08:11

Shahin Al Kabir Mitul


Note: the routes are case sensitive so make sure you match the casing across

This worked for me for Angular 8:
From the parent component / page, to navigate to the sub page using typescript:

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

My router in the parent's module looks like this:

const routes: Routes = [
  {
    path: '',
    component: MyPage,
    children: [
      { path: 'subPage', component: subPageComponent}
    ]
  }
];

And on the parent's html page use the following to navigate using a link:

<a [routerLink]="'subPage'">Sub Page Link</a>
<router-outlet></router-outlet>
like image 4
Tony Avatar answered Nov 14 '22 06:11

Tony