Angular RouterLink relative path does not work in component having empty path
Asked Answered
E

1

1

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?

Empson answered 16/4, 2020 at 20:7 Comment(0)
E
1

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

Empson answered 16/4, 2020 at 20:7 Comment(3)
But, For my project that I migrated from Angular 11.2.2 to 15.2.8. Throws this error at compile time [Argument of type '{ useHash: true; relativeLinkResolution: string; }' is not assignable to parameter of type 'ExtraOptions'. Object literal may only specify known properties, and 'relativeLinkResolution' does not exist in type 'ExtraOptions'. 44 relativeLinkResolution: 'legacy']. [it was working fine till last version] the path should resolve like this => [localhost:4200/#/dashboard]Duvalier
@Duvalier corrected is now a default behavior for angular 15. You app must work fine with it. github.com/angular/angular/issues/37355#issuecomment-736521495Empson
Yes it works find , after the relativeLinkResolution is removed . Like this ----> imports: [RouterModule.forRoot(routes)]. ------------- In Angular15, relativeLinkResolution is not one of the property of ExtraOptions interface which is the second argument in forRoot(Routes[] , ExtraOptions)Duvalier

© 2022 - 2024 — McMap. All rights reserved.