Search code examples
angular2-routing

How to split app-routing.module.ts in multiple files in Angular 2?


Considering the image, I have a component (1) + module (2) + routing (3)(in "app-routing.module.ts"). To avoid too much code in "app-routing.module.ts", I want to move the routing code (3) in other file (suppose "product.routes.ts"). How can I do this considering I'm using Angular 2? Thanks! enter image description here


Solution

  • This would be the AppComponentRoutingModule which I use, which can be extended with further files, usually that is one routes file per nested routing (to be imported in the corresponding module). The components and routes may vary, but it generally works alike this (guards skipped for the sake of brevity):

    Create src/app/routes/app.routes.ts with content alike:

    import { Routes } from '@angular/router';
    import { ErrorPage } from 'src/app/pages/error/error.page';
    
    export const appRoutes: Routes = [
      { path:          '', redirectTo: 'home', pathMatch: 'full' }, // main entry point.
      { path:      'home', loadChildren: () => import('src/app/pages/home/home.module').then(m => m.HomeModule) },
      { path: 'error/:id', component: ErrorPage, pathMatch: 'full' },
      { path:        '**', redirectTo: '/error/404' }
    ];
    

    The nested routes don't look much different, for example src/app/routes/home.routes.ts:

    export const homeRoutes: Routes = [{
      path: '',
      component: HomePage,
      children: [
        ...
      ]
    }];
    

    Create src/app/app.component.routing.module.ts with content alike:

    import { NgModule } from '@angular/core';
    import { PreloadAllModules, RouterModule } from '@angular/router';
    import { appRoutes } from './routes/app.routes';
    
    @NgModule({
      imports: [
        RouterModule.forRoot(appRoutes,{preloadingStrategy: PreloadAllModules})
      ],
      exports: [ RouterModule ]
    })
    export class AppComponentRoutingModule {}
    

    Then import AppComponentRoutingModule in app.module.ts:

    import { RouterModule } from '@angular/router';
    import { AppComponent } from 'src/app/app.component';
    import { AppComponentRoutingModule } from 'src/app/app.component.routing.module';
    ...
    
    @NgModule({
      declarations: [ AppComponent ],
      imports: [
        RouterModule,
        AppComponentRoutingModule,
        ...
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule {}
    

    In order to enable verbose logging, enableTracing: true is your friend.