Search code examples
angularangular-routing

Angular merge routes of child modules


I am dividing my angular application into modules. For a module i have a view component and an edit component. The view components have their own url (e.g. '/users').

The edit components have a common parent url (e.g. '/admin/users').

 - UserModule
     - UserPageComponent ('/user/:username')
     - UserEditComponent ('/admin/user/:username')
 - GroupModule
     - GroupPageComponent ('/group/:groupname')
     - GroupEditComponent ('/admin/group/:groupname')

This does work and the urls are accessible.

If i look at the routes with augury i see that angular defined each '/admin' route as a separate route: (3 admin routes with 1 child each)

- Root
    - Admin
        - Users
    - Admin
        - Groups
    - Admin
        - Permissions

But because of this the wrapping admin component is reloaded every time a user switches between a pages (resetting the menu state in the admin component).

Is it possible to define these routes like this? (1 admin route with 3 children)

- Root
    - Admin
        - Users
        - Groups
        - Permissions

currently i define the routes in each submodule using this code (Replacing Users for each other module).

export const routes: Routes = {
  path: 'admin',
  component: AdminComponent,
  children: [
    {
      path: 'Users',
      component: UserEditComponent
    }
  ]
}];

@NgModule({
  imports: [RouterModule.forChild(routes)]
})
export class UserRoutingModule{}

And in the main routing module i just do:

@NgModule({
  imports: [RouterModule.forRoot([])],
  exports: [RouterModule]
})
export class AppRoutingModule {}

i tried setting onSameUrlNavigation to 'ignore' on the forRoot() call but unfortunately this didn't change anything.


Solution

  • You can have and AdminModule, and inside this module inject your child modules (with their own routing)

    For example I have a main app routing that load 2 lazy modules:

    • Authentication, here I have a routing for register and login (both components)
    • Dashboard (Admin), inside here I have another modules such as ClientModule and ProductModule wich are display in a outer-outlet inside dashboard component that also contain a sidenav and a toolbar.

    enter image description here

    OBSERVATION:

    I would advice to use lazy modules at some routes for clean code, independency at unit testing and improve app performance.

    enter image description here

    I have this example at my github repo, if you have some questions or suggestions Im available to listen: https://github.com/danidelgadoz/ngx-admin