是否可以使用children
配置“终端”路线,或者换句话说,具有“可选”children
的路线。使用可选子项创建路线
我想创建一个可路由的主/细节视图,其中的细节最初不显示,并且当详细视图打开时,列表不会被销毁。
例如,导航至/a
,然后在不破坏a
的情况下导航至/a/1
。
首次尝试:
const routes: RouterConfig = [
//...
{ path: 'a', component: AListComponent, children: [
{ path: ':id', component: ADetailsComponent }
]},
//...
];
...这个配置,下面的错误被抛出:
EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: 'a'
第二次尝试:
const routes: RouterConfig = [
//...
{ path: 'a', component: AListComponent },
{ path: 'a', component: AListComponent, children: [
{ path: ':id', component: ADetailsComponent }
]},
//...
];
...列表组件被销毁并重新创建,即如果它具有用户输入,则值将消失。
第三次尝试 - 创建一个“Empty”组件并默认加载它。
const routes: RouterConfig = [
//...
{ path: 'a', component: AListComponent, children: [
{ path: '', component: EmptyComponent },
{ path: ':id', component: ADetailsComponent }
]},
//...
];
...作品,但感觉像一个解决方法。
有没有更好的方法?
如何使用不显示任何“可选”路由的虚拟组件? AFAIK你正在寻找什么不被支持。 –
@GünterZöchbauer,感谢您的评论。你的建议基本上是我的第三次尝试 - 它有效,但并不“感觉正确”。但是,如果您将您的评论作为答案,我很乐意接受它。这种方法如何看待你?英雄之旅(https://angular.io/docs/ts/latest/tutorial/toh-pt2.html)使用* ngIf来实现这一点,但使用路由器感觉好一点。如果空分量方法看起来不太可怕,那么至少在目前这可能是一种前进的方式。 –
恕我直言,如果'ngIf'非常合适,主要取决于您是否想在URL中反映状态。如果这不是'ngIf'没有必要或有用的话,那应该没问题。 –