Use child routes, but do not render them in a router-outlet

pronngo Source

I have a code where router config looks like:

  {
    path: 'users',
    component: UsersComponent,
    children: [
      {
        path: 'add',
        component: AddUserComponent
      }
    ]
  }

By that I'd like to have two pages:

  • /users - which shows users list
  • /users/add - which shows a form to add a new user

But I don't what to have nested router-outlet tags. Both pages I'd like to render in the same, main container which is app-root. I know I can do that just by:

  {
    path: 'users',
    component: UsersComponent
  },
  {
    path: 'users/add',
    component: AddUserComponent
  }

But you probably agree with me that this is not a nice solution and it'd be good to use children construction.

How can I do that?

javascriptangular

Answers

answered 8 months ago smnbbrv #1

You don't need a nested route if you don't have a component assigned to the route => just don't add the component to the definition of the users route and make a dedicated empty path for the list page:

  {
    path: 'users',
    children: [
      {
        path: '',
        component: UsersComponent
      },
      {
        path: 'add',
        component: AddUserComponent
      }
    ]
  }

There is a drawback here: if you use a routerLink inside of UsersComponent where you will use relative path, the empty path will behave still as a path. So you would need to use relative path similar to ../add and not ./add as normally one would think

answered 8 months ago Pugazhavan Suriya Kumar #2

Check this code:

{
    path: 'users',
    component: UsersComponent,
    children: [
      {
        path: '',
        component: UsersComponent
      },
      {
        path: 'add',
        component: AddUserComponent
      }
    ]   
}

comments powered by Disqus