简体   繁体   中英

Angular - Issue on navigating from one sibling to another lazy loaded component with a parent with path parameters

I'm using angular 9 and I'm using Lazy-loading feature modules. I'm not able to navigate from one component to the sibling one. I have the following structure:

src/app/app-routing.module.ts

const routes: Routes = [
  {
    path: 'module1',
    loadChildren: () => import('./module1.module').then(m => m.Module1Module)
  },
  {
    path: 'module2/:id',
    loadChildren: () => import('./module2.module').then(m => m.Module2Module)
  }
];

src/app/app.component.html

<button routerLink="/module1">Go to Module1</button>
<button routerLink="/module2/MyId">Go to Module1</button>
<router-outlet></router-outlet>

src/app/module2/module2-routing.module.ts | similar rc/app/module1/module1-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: Module2Component,
    children: [{
    path: '',
    redirectTo: 'child1',
    pathMatch: 'full'
  },
  {
    path: 'child1',
    loadChildren: () => import('./child1.module').then(m => m.Child1Module)
  },
  {
    path: 'child2',
    loadChildren: () => import('./child2.module').then(m => m.Child2Module)
  }
  ]
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class Module1RoutingModule { }

src/app/module2/child1/child1.component.html

<button routerLink="../child2">Go to Module2/MyId/child2</button>

My problem is that from home to module1 I have the correct url, ie http://localhost:4200/module1 but if I would like to module2/MyID/child2 from module2/MyID/child1 then it goes to http://localhost:4200/module2/MyID/child1/child2 instead of http://localhost:4200/module2/MyID/child2

Thanks

Just in case somebody has the same issue, the solution I found is to use absolute path and getting the Path Params from activatedRoute: ActivatedRoute. So I have:

src/app/module2/child1/child1.module.ts

baseUrl = '/module2/{id}';
constructor(private activatedRoute: ActivatedRoute)
ngOnInit() {
    this.baseUrl = this.baseUrl.replace('{id}', this.activatedRoute.snapshot.params.id);
}

src/app/module2/child1/child1.component.html

<button routerLink="{{baseUrl}}/child2">Go to Module2/MyId/child2</button>

Try to change routerLink="/module2" .

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