Search code examples
angularangular-routing

Understanding Angular routing at feature module


I have routing defined as so in my app-routing.module.ts

[
   {path: 'xyz', loadChildren: './child/child.module#ChildModule'}
]

and in child-routing.module.ts as

[
    {path: '', component: ChildComponent},
    {path: ':id', component: ChildComponent}
]

When I visit the route localhost:4200/xyz it loads the ChildComponent which is expected.

But when I go to localhost:4200/ it loads the ChildComponent. This wasn't expected as I assumed it is parent_route i.e xyz plus child_route.

How do I restrict angular from loading ChildComponent on /

Example posted on StackBlitz https://stackblitz.com/edit/angular-xts7bc


Solution

  • You are trying to lazy-load the ParentModule and the ChildModule, but you have imported both of them, in AppModule and ParentModule respectively. The router are not matching to the defined routes in Parent and AppModule, but they match the ChildModule, hence you get that component even on the root ('/').

    To fix this, remove the ParentModule from the imports array of AppModule and remove ChildModule from the imports of ParentModule.