13

I have a button in a page like this:

<button [routerLink]="['../edit', 14]">Test</button>

So, if I'm at http://localhost/dashboard and click the button, I'm redirected to http://localhost/dashboard/edit/14, which is exactly what I expected.

Now I need to do the same in Typescript. I injected the Router service in my class and tried the following:

this.router.navigate([`../edit/${item.id}`]);

this.router.navigate([`/edit/${item.id}`]);

this.router.navigate([`edit/${item.id}`]);

But none is working, all of them redirect me to my starting page with no errors.

Does the Router need some extra setup?

rbasniak
  • 4,484
  • 11
  • 51
  • 100

2 Answers2

23

You need to specify that you are routing relative to the current route. Here is how this can be done:

@Component({...})
class ChildComponent {
  constructor(private router: Router, private route: ActivatedRoute) {}

  go() {
    this.router.navigate([`../edit/${item.id}`], { relativeTo: this.route });
  }
}

Here are Docs describing the relativeTo property of the NavigationExtras class

Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
1

Remember to add the children routes on your app.module.ts:

RouterModule.forRoot(
    [{
        path: 'dashboard',
        component: Dashboard,
        children: [
            {
                path: 'edit/:id',
                component: EditComponent,
            }]
    }])
dlcardozo
  • 3,953
  • 1
  • 18
  • 22
  • Yes, it's done. I didn't include in the answer because I don't think it's a problem with the routes setup, because I can navigate to it using the `routerLink` in HTML – rbasniak Feb 01 '17 at 18:48