Search code examples
angularjsangulartypescriptangular-routingangular-lazyloading

Facing issue while Lazy loading a module ( Cannot find module)


I am working on creating lazy loaded modules In spite of all my efforts, I think I am missing something here due to which I'm unable to load modules on demand.

I have my project structure as below:

screenshot of project structure

app
 -users
  -homeComponent
  -signupComponent 
  -users.routing.module.ts
  -users.module.ts
 -list
  -createListComponent
  -dashboardComponent 
  -list.routing.module.ts
  -list.module.ts

users-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { SignupComponent } from './signup/signup.component';

const routes: Routes = [
  {
    path: "",
    component: HomeComponent
  },
  {
    path: "/signup",
    component: SignupComponent
  }

];

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

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'signup',
    loadChildren: './app/users/users.module#UsersModule',
  },
];

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

I have added relative path in my loadChildren tag, but I am still getting an error saying "cannot load module". I have tried different websites but I feel I am missing a basic part here.

screenshot of error

Any help would be appreciated.


Solution

    1. Add users component in the users module.
    2. Add users component will be the container where other child component get loaded.
    3. Add <router-outlet></router-outlet> in the app componentcompoent

    enter image description here

    users-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { HomeComponent } from './home/home.component';
    import { SignupComponent } from './signup/signup.component';
    import { UsersComponent } from './users.component';
    
    const routes: Routes = [
      {
        path: '',
        component: UsersComponent, // will be bootstrap component for users module
        children: [ // will children for user module
          {
            path: 'signup',
            component: SignupComponent,
          },
          {
            path: 'home',
            component: HomeComponent,
          },
        ]
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule],
    })
    export class UsersRoutingModule { }
    

    Here is working demo https://stackblitz.com/edit/angular-ivy-j6wtlk