I have a root app component with a router-outlet, and the routes are loaded from a home module routes which uses lazy loading with loadchildren in its children routes. There is a router-outlet in the home component and also there is router-outlets in all the child modules of the home which are lazyloaded. The routes are working fine but the child routes are also getting loaded in root router-outlet. Eg:- the component 'testCreateComponent' is loading with localhost:4200/test/create and also localhost:4200/create.
Sample code levels are as follows:-
app.component.html
<div>app</div>
<router-outlet></router-outlet>
app-routing.module.ts
export const APP_ROUTES: Routes = [
{path: '**', redirectTo: '', pathMatch: 'full'}
];
home.component.html
<div>home</div>
<router-outlet><router-outlet>
home-routing.module.ts
const routes: Routes = [{
path: '',
component: HomeComponent,
canActivate: [LoggedUserGuard],
canActivateChild: [AuthGuard],
children: [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{
path: 'test',
loadChildren: () => testModule
},
{
path: 'dashboard',
component: DashboardComponent,
data: {
breadcrumb: 'Dashboard'
}
},
{
path: 'dummy',
loadChildren: () => dummyModule,
}
]
}];
testComponent.html
<div>Test</test>
<router-outlet></router-outlet>
test-routing.module.ts
const routes: Routes = [{
path: '',
component: TestComponent,
children: [
{path: '', component: ListComponent,
data: {
breadcrumb: 'List'
}},
{path: 'create', component: testCreateComponent},
{ path: 'detail/:id',
component: TestEditComponent,
}
]
}];
The issue is likely how you import your lazily loaded modules.
We had a similar issue with lazily loaded modules, which were erroneously imported explicitly/eagerly as well in the TypeScript import section at the top of a module's file (instead of inline only in the loadChildren
function).
In order to easily find them in a huge project, I think we configured the router with preloadingStrategy: PreloadAllModules
, logged out router.config
, and inspected the routes and their components. Removing the imports from the TypeScript import section at the top of the module (and only leaving them inline) fixed the issue.
Try removing
import { testModule } from "./path/to/file/containing/test.module";
from the top of your file and instead use only the following in the route
loadChildren: () => import("./path/to/file/containing/test.module").then((m) => m.testModule)
Also check out the Angular Docs: Troubleshooting lazy-loading modules
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With