16

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?

2 Answers 2

27

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

Sign up to request clarification or add additional context in comments.

1 Comment

import { ActivatedRoute, Router } from '@angular/router'; // This is how you import Route and ActivatedRoute
1

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

RouterModule.forRoot(
    [{
        path: 'dashboard',
        component: Dashboard,
        children: [
            {
                path: 'edit/:id',
                component: EditComponent,
            }]
    }])

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.