Search code examples
angularangular2-routingangular2-router3

Creating a route with optional children


Is it possible to configure a "terminal" route with children, or in other words, a route with "optional" children.

I'm trying to create a routable master/detail view, where the details are not displayed initially, and the list is not destroyed when the details view is opened.

For example, navigate to /a, and then, without destroying a, navigate to /a/1.

First attempt:

const routes: RouterConfig = [
  //...
  { path: 'a', component: AListComponent, children: [
    { path: ':id', component: ADetailsComponent }
  ]},
  //...
];

... with this configuration, the following error is thrown:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: 'a'

Second attempt:

const routes: RouterConfig = [
  //...
  { path: 'a', component: AListComponent },
  { path: 'a', component: AListComponent, children: [
    { path: ':id', component: ADetailsComponent }
  ]},
  //...
];

... the list component is destroyed and recreated, i.e. if it has user inputs, the values are gone.

Third attempt - create an "Empty" component and load it by default.

const routes: RouterConfig = [
  //...
  { path: 'a', component: AListComponent, children: [
    { path: '', component: EmptyComponent },
    { path: ':id', component: ADetailsComponent }
  ]},
  //...
];

... works, but feels like a workaround.

Is there a better way?


Solution

  • An empty dummy component that doesn't show anything like shown in your 3rd attempt is the best way in my opinion.