Search code examples
angulartypescriptangular-routingeager-loading

How to use a default layout while keeping the route definitions in their respective eager-loaded module


I have the some routes defined in the AppRoutingModule and they use a default layout -

const routes: Routes = [
    {
        path: '',
        component: DefaultLayoutComponent,
        children: [
            { path: 'home', component: HomeComponent },
            { path: 'about', component: AboutComponent }
        ]
    }
];

Now I want to add an eager-loaded feature module, AuthModule, with the following routes -

{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent }

I want RegisterComponent and LoginComponent to use the default layout, and for that I need to define these two new routes in the AppRoutingModule like -

const routes: Routes = [
    {
        path: '',
        component: DefaultLayoutComponent,
        children: [
            { path: 'home', component: HomeComponent },
            { path: 'about', component: AboutComponent },
            { path: 'register', component: RegisterComponent },
            { path: 'login', component: LoginComponent }
        ]
    }
];

But I don't want to move these routes in AppRoutingModule. I want them contained in their respective routing module, the AuthRoutingModule and still use the default layout. How can I do that?


Solution

  • You can use the loadChildren property and return the module directly in the callback function.

    const routes: Routes = [
        {
            path: '',
            component: DefaultLayoutComponent,
            children: [
                { path: 'home', component: HomeComponent },
                { path: 'about', component: AboutComponent },
                { path: '', loadChildren: () => AuthModule }  // <---
            ],   
        }
    ];