Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
rbasniak Avatar asked Feb 01 '17 18:02

rbasniak


People also ask

What is routing in typescript?

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.


2 Answers

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

like image 186
Teddy Sterne Avatar answered Oct 11 '22 19:10

Teddy Sterne


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

RouterModule.forRoot(
    [{
        path: 'dashboard',
        component: Dashboard,
        children: [
            {
                path: 'edit/:id',
                component: EditComponent,
            }]
    }])
like image 1
dlcardozo Avatar answered Oct 11 '22 19:10

dlcardozo