Search code examples
angularlazy-loading

Angular - Lazy Loading Same Module with Two Routes


I have this routing currently in my app-routing module:


{
    path: 'school',
    component: SchoolComponent
  },
{
    path: 'student',
    component: StudentComponent
  },
  {
    path: 'student/view',
    component: StudentDetailsComponent
  },
  {
    path: 'student/view/:id',
    component: StudentDetailsComponent
  }

Now I am trying to do lazy loading to a StudentModule with a student-routing module for the 3 paths: student, student/view and student/view:id.

How I can do this to the app-routing module and student-routing module?

Here the last two paths are mapped to same component.

I am new to angular and could not find a proper example.


Solution

  • Assuming we have a student module created, we can add children routes to simplify the /student/view and /student/view:param routes so that we do not have to define /student twice. The outer path will be '' so that this is the default route when the module is loaded.

    student-routing.module.ts

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { StudentComponent } from './student.component';
    import { StudentDetailsComponent } from '../student-details/student-details.component';
    
    const routes: Routes = [
      {
        path: '',
        component: StudentComponent,
        children: [
          {
            path: 'view',
            component: StudentDetailsComponent,
          },
          {
            path: 'view/:id',
            component: StudentDetailsComponent,
          },
        ],
      },
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule],
    })
    export class StudentRoutingModule {}
    

    To then lazy load the student module from your app module, you can import it as so: (please note this is where we define the root path for the module student)

    app.routes.ts:

    import { Routes } from '@angular/router';
    
    export const routes: Routes = [
      {
        path: 'student',
        loadChildren: () =>
          import('./student/student.module').then((m) => m.StudentModule),
      },
    ];
    

    The routing will work in your browser as:

    • yourdomain/student/view -> student details component
    • yourdomain/student/view/1234 -> student details component
    • yourdomain/student -> student component