简体   繁体   中英

Calling the Angular router in TypeScript

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?

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,
            }]
    }])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM