Search code examples
angularlazy-loadingangular-routing

Angular lazy loading routing


I have lazy load app routing like below:

app.routing.ts

{
  path: 'reports',
  loadChildren: () => import('../Reporting/reporting.module').then(m => m.ReportingModule)
},
{
  path: 'report-builder',
  loadChildren: () => import('../Reporting/reporting.module').then(m => m.ReportingModule)
},

My lazy load module routes look like this

const routes: Routes = [
    {
      path: '',
      children: [
        { path: '', component: ReportsComponent },
        { path: ':id',component: ViewReport},
        { path: '**', component: ViewReport }
      ]
    },
    {
      path: '',
      children: [
        { path: '', component: ReportBuilderComponent },
        { path: 'edit/:id', component: DesignReport },
        { path: '**', component: DesignReport }
      ]
    }

I am trying to achieve, when user clicks on reports route, navigate to default Reportscomponent and when clicked on reportBuilder route, navigate to ReportBuilderComponent.

How to achieve this.


Solution

  • Method 1

    Create two modules one for reports and one for report-builder.

    app.report-routing.ts

    const routes: Routes = [
        {
           path: '',
           children: [
               { path: '', component: ReportsComponent },
               { path: ':id',component: ViewReport},
               { path: '**', component: ViewReport }]
        }
    ]
    

    Configure above routes in report.module

    app.report-builder-routing.ts

    const routes: Routes = [
        {
          path: '',
          children: [
            { path: '', component: ReportBuilderComponent },
            { path: 'edit/:id', component: DesignReport },
            { path: '**', component: DesignReport }
          ]
        }
    ]
    

    configure above routes in report-builder.module

    app.routing.js

    {
      path: 'reports',
      loadChildren: () => import('../Reporting/report.module').then(m => m.ReportingModule)
    },
    {
      path: 'report-builder',
      loadChildren: () => import('../Reporting/report-builder.module').then(m => m.ReportBuilderModule)
    }
    

    Method 2

    app.report-routing.ts

    const routes: Routes = [
        {
          path: '',
          children: [
            { path: '', component: ReportsComponent },
            { path: ':id',component: ViewReport},
            { path: '**', component: ViewReport }
          ]
        },
        {
          path: 'builder',
          children: [
            { path: '', component: ReportBuilderComponent },
            { path: 'edit/:id', component: DesignReport },
            { path: '**', component: DesignReport }
          ]
        }
    

    app.routing.ts

    {
      path: 'report',
      loadChildren: () => import('../Reporting/reporting.module').then(m => m.ReportingModule)
    }
    

    I hope this works for you.

    Reference Angular: Lazy loading feature modules