Angular Router:定义子路由

通过在路由器配置中使用子路由,可以很容易地在您的ANGLE应用程序中创建任何类型的路由层次结构。

<$>[注]以下内容涵盖了角度2+应用程序的路径选择。<$>

要定义子路由,只需添加一组附加的路由配置对象,作为父配置中子关键字的一部分。以下是一个配置示例:

1const routes: Routes = [
2  { path: '', component: ParentComponent, children: [
3    { path: 'red', component: ChildComponent },
4    { path: 'blue', component: AnotherChildComponent }
5  ] }
6];

别忘了在任何父组件的模板中添加一个路由器插座指令:

1<router-outlet></router-outlet>

在这样的配置下,可用的路由将是/、/红色和/蓝色(例如:http://localhost:4200/red )


子路由也可以有自己的子路由:

 1const routes: Routes = [
 2  { path: '', component: ParentComponent, children: [
 3    { path: 'red', component: ChildComponent, children: [
 4      { path: 'knock-knock', component: SubChildComponent, children: [
 5        { path: 'neo', component: SubSubChildComponent }
 6      ] },
 7    ] },
 8    { path: 'blue', component: AnotherChildComponent }
 9  ] }
10];

现在你可以通过导航到/red/Knoke-Knoke/neo🐇到达兔子洞的尽头

无路径路由

你不一定要有通向所有路线的路径。让我们以上一个配置的这个变体为例:

 1const routes: Routes = [
 2  { path: '', component: ParentComponent, children: [
 3    { path: '', component: ChildComponent, children: [
 4      { path: 'knock-knock', component: SubChildComponent, children: [
 5        { path: 'neo', component: SubSubChildComponent }
 6      ] },
 7    ] },
 8    { path: 'blue', component: AnotherChildComponent }
 9  ] }
10];

请注意,包含ChildComponent组件的路由没有路径。这意味着用户将直接导航到/KUKE-KNOCK/neo,但ChildComponent仍将被实例化,其子组件仍将被插入其路由器插座。

无组件路由

也可以有一个没有组件的父路由:

 1const routes: Routes = [
 2  { path: '', component: ParentComponent, children: [
 3    { path: 'red', children: [
 4      { path: 'knock-knock', component: SubChildComponent, children: [
 5        { path: 'neo', component: SubSubChildComponent }
 6      ] },
 7    ] },
 8    { path: 'blue', component: AnotherChildComponent }
 9  ] }
10];

在这种配置下,用户仍然可以导航到/red/Knoke-Knoke/neo,但SubChildComponent将插入到ParentComponent的路由器插座中。

如果我们的路径为我们提供了我们希望在组件链的其余部分或兄弟组件中可用的数据或参数,这可能会很有用。让我们用一个例子来说明:

1const routes: Routes = [
2  { path: '', component: ParentComponent, children: [
3    { path: ':choice', children: [
4      { path: 'neo', component: ChildComponent },
5      { path: 'trinity', component: AnotherChildComponent }
6    ] }
7  ] }
8];

通过这种配置,ChildComponent 和** AnotherChildComponent** 都可以访问choice参数,并且我们不必仅仅为了包装两个兄弟组件而涉及另一个虚拟组件。

Published At
Categories with 技术
Tagged with
comments powered by Disqus