[Fixed] 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' },

  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] }];

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

Here is my AppModule

 declarations: [AppComponent],
   imports: [
     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?


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

Leave a Reply

(*) Required, Your email will not be published