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?
Implementing React Router v6 with code splitting in a React Typescript project. React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
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
Remember to add the children routes on your app.module.ts:
RouterModule.forRoot(
[{
path: 'dashboard',
component: Dashboard,
children: [
{
path: 'edit/:id',
component: EditComponent,
}]
}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With