Jonathan Solorzano
Jonathan Solorzano

Reputation: 7032

How to do routing on nested modules in Angular?

I got a Module hierarchy like this:

app

-- module1
   - submodule1
   - submodule2

I want to know how to do the routing from submodules to modules, and from modules to the main app module.

So far I can route from modules to main app module like this:

app.module.ts - Main Module

...imports

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    AppRoutingModule,

    //Feature Modules
    Module1,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

app.routing.ts

import { RouterModule } from '@angular/router';

export const AppRoutingModule = RouterModule.forRoot([
  { path: '', component: AppComponent },
  { path: 'module1', loadChildren: './feature/module1/module1.module#Module1' }
]);

module1.module.ts - Level 1 Module

...imports

@NgModule({
  imports: [
    SubModule1,
    SubModule2,
    Module1RoutingModule
  ],
  declarations: [Module1Component],
})
export class Module1 { }

module1.routing.ts

import { RouterModule } from '@angular/router';
import {Module1Component} from "./module1.component";

export const Module1RoutingModule = RouterModule.forChild([
  { path: '', component: Module1Component },
  { path: 'submodule1', loadChildren: '.submodule1/submodule1.module#Submodule1Module' },
]);

And here's where I don't know how to route the submodule routes...

submodule1.module.ts - Level 2 Module

...imports

@NgModule({
  imports: [
    Submodule1RoutingModule
  ],
  declarations: [Submodule1Component],
})
export class Submodule1Module { }

Here's where I need help figuring out how to route:

submodule1.rounting.ts

import { RouterModule } from '@angular/router';
import {Submodule1Component} from "./submodule1.component";

export const Submodule1RoutingModule = RouterModule.forChild([
  { path: '', component: Submodule1Component }
]);

Upvotes: 2

Views: 3017

Answers (1)

Christian Abella
Christian Abella

Reputation: 5797

You can add a 'children' in your route to define the sub-routes. Sub-routes defined here will only be visible inside the submodule route.

{ path: 'submodule', component: Submodule1Module,
    children: [
      { path: 'sub-route1', component: SubRoute1 },
      { path: 'sub-route2', component: SubRoute2 }
    ]
}

Upvotes: 3

Related Questions