Search code examples
angularangular9angular-router

Angular: How to prevent direct access to lazy child module route via browser


I am developing a multi-module application using Angular 9. Here is my main application routing module.

Here is AppRoutingModule and it loads lazy DemoModule.

const routes: Routes = [
{
    path: '',
    component: AdminLayoutComponent,
    canActivate: [SecGuard],
    children: [
      {
        path: 'demo',
        loadChildren: () => import('demo').then((m) => m.DemoModule),
       },
      { path: 'not-found-page', component: NotFound404PageComponent, canActivate: [SecGuard] },
    ],
  },

  { path: '**', redirectTo: 'not-found-page' },
];

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

Here is the code of DemoRoutingModule

export const CTS_ROUTES: Routes = [{ path: 'dashboard', component: DashboardComponent, canActivate: [SecGuard] }];

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

Here is my AppModule

@NgModule({
 declarations: [AppComponent],
   imports: [
     BrowserModule,
     BrowserAnimationsModule,
      CommonModule,
     CoreModule.forRoot(configuration),
     DemoModule,
     AppRoutingModule,
      ],
     providers: [],
     bootstrap: [AppComponent],
   })
  export class AppModule {}

Now when I access http://localhost:4200/demo/dashboard everything is normal.

enter image description here

But when I try to access http://localhost:4200/dashboard which I don't want to do. Then the result is like below image.

enter image description here

I want to access child components (which in this case DashboardComponent) only via the parent path /demo/dashboard.

How can I achieve this functionality? Any idea?


Solution

  • As @GowthamRajJ had commented, Angular resolves lazy loaded modules from the routing module. No Need to import lazy-loaded module inside your AppModule.