Search code examples
angularangular4-router

Angular4 routing in module and submodule


I plan to create a structure as below (Routes in each routing.ts is to illustrate my idea)

app.module.ts
app.routing.ts  // Routes = [{ path: 'modA', module: moduleA }, { path: 'modB', module: moduleB }]
moduleA
  -- moduleA.module.ts
  -- moduleA.routing.ts  // Routes = [{ path: '', component: ListComponent }, { path: 'new', component: CreateComponent }]
  -- list.component.ts
  -- create.component.ts
moduleB
  -- moduleB.module.ts
  -- moduleB.routing.ts  // Routes = [{ path: 'a', component: AbcComponent }, { path: 'z', component: XyzComponent }]
  -- abc.component.ts
  -- xyz.component.ts

I want to group whatever in moduleA just in moduleA.module including its routing. Same as moduleB.

Then I wish to expose moduleA and moduleB to app.routing for me to register its module path. I expect:

/modA           show list component in moduleA
/modA/new       show create component in moduleA
/modB/a         show abc component in moduleB
/mobB/z         show xyz component in moduleB

How can I create above structure in Angular4? Please provide same workable code if possible.


Solution

  • I would suggest that since you are already breaking down the relative pieces into modules that you use lazy-loading which will have a performance increase in your app. By using lazing loading you will get the functionality you want right out of the box. Each module will define its routing relative to itself and the module will be served from the base route specified in the app.routing file.

    app.routing.ts

    RouterModule.forRoot([{
        path: 'modA',
        loadChildren: './moduleA/moduleA.module#ModuleA'
    }, {
        path: 'modB',
        loadChildren: './moduleB/moduleB.module#ModuleB'
    }]
    

    moduleA.routing.ts

    RouterModule.forChild([{
        path: '',
        component: ListComponent 
    }, {
        path: 'new',
        component: CreateComponent
    }]
    

    moduleB.routing.ts

    RouterModule.forChild([{
        path: 'a',
        component: AbcComponent 
    }, {
        path: 'z',
        component: XyzComponent
    }]