Search code examples
angularangular-routingangular-router

Angular - redirect to same component with different parameter


So in angular I've nested routing, lets say:

domain.com/dashboard/list/:listId/:listName/details/:detailsName/:detailsId
  • Dashboard is separate module

  • List is separate module

  • Details is separate module

Now, on details page, I've also small component with similar to list that I've on list page, and thats way I want also redirect user to the same details component but with different parameters.

So let's from :

domain.com/dashboard/list/1/test_list_name/details/test_details_name/4

to

domain.com/dashboard/list/1/test_list_name/details/another_test_details_name/8

RouterLink:

<h5 [routerLink]="['details', id, name]"></h5>

Unfortunately I'm always redirected to /dashboard. I tried it also with setting routeReuseStrategy to false. But without success.

What I'm doing wrong?

@Edit, stackblitz:

https://stackblitz.com/edit/angular-q8fasa

In stackblitz example I just want to open another dashboard-second component(with different parameters) from dashboard-second component. In this example I've used only one nested routing, but issues is exactly same.

Sorry for quite ugly example, but I believe you will understand my problem.


Solution

  • Using RouterModule.forRoot(routes, { enableTracing: true }), I see the following in the console:

    Event: NavigationEnd NavigationEnd(id: 3, url: '/dashboard/dashboard-second/original-name-something-bla-bla/87/dashboard-second/other-name/11', urlAfterRedirects: '/dashboard') NavigationEnd {id: 3, url: "/dashboard/dashboard-second/original-name-something-bla-bla/87/dashboard-second/other-name/11", urlAfterRedirects: "/dashboard"}

    So it has dashboard-second twice.

    I had to change the routerlinks to:

    <h5 [routerLink]="['../../../../dashboard-second', 'other-name', 11]" >Go to dashboard-second 1</h5> 
    

    It fixes the problem. The 4 .. is to go back to /dashboard. Each .. go to:

    1. 87 (ie: /87/.. = /87)
    2. original-name-something-bla-bla
    3. dashboard-second
    4. /dashboard

    It's a bit unintuitive that it takes 4 .., I thought it would have taken 3, but it makes sense because it's relative. So you end up doing:

    /dashboard/dashboard-second/original-name-something-bla-bla/87/../../../../dashboard-second/other-name/11

    which resolves to:

    /dashboard/dashboard-second/other-name/11

    You can also set an absolute path, with the caveat that if you move the route /dashboard-second around, it is more likely you have to update the routerLink when using absolute paths:

    <h5 [routerLink]="['/dashboard/dashboard-second', 'name-name-name', 13]" >Go to dashboard-second 3</h5>