Search code examples
angularurlrouterrouterlink

Angular RouterLink relative path does not work in component having empty path


I have my child path defined as

{ path: '', component: CartMainComponent, pathMatch: 'full' }

The whole path looks like this when I am in CartMainComponent http://mystype.com/brand/MyBrandId/cart In the cart I want to navigate to /brand/MyBrandId/cart so I used routerLink="../cart" in html. But this gave me next error

Error: Cannot match any routes. URL Segment: 'brand/Rotiform/cart/catalog'

Only when I do routerLink="../../../cart" it works

This is illogical, even if the empty path is treated as an additional level of relative path. Still I expect to use '..' only twice but not three times

Is it possible to fix it so I can relatively go through route without thinking if there are any empty paths?


Solution

  • Yes, the Angular team added a fix for this issue, but you need to enable it manually by adding

    relativeLinkResolution: 'corrected' in root router configuration. I.e.

    @NgModule({ imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'corrected'})], exports: [RouterModule] })

    But please, note that this 'bugfix' didn't solve the whole bug. This is why it is not enabled by default. This PR describes the problem: https://github.com/angular/angular/issues/26983 Please keep it in mind.

    RelativeLinkResolution is also discussed in this github thread https://github.com/angular/angular/issues/13011