Angular 多重路由

文中使用的工具或者包的版本:Angular CLI 11.0.6

文中 Demo 链接:https://stackblitz.com/edit/angular-route-outlet-3crvst

配置

首先我们在模板中定义多个路由出口,比如:

<router-outlet></router-outlet>
<router-outlet name="second"></router-outlet>
<router-outlet name="third"></router-outlet>

注意路由出口的名称不能动态设置或更改。如果未设置,则默认值为 “primary”。

然后我们给每个路由出口配置对应的路由,比如:

const routes: Routes = [
  { path: "route1", component: Route1Component },
  { path: "route2", component: Route2Component },
  { path: "secondRoute1", component: SecondRoute1Component, outlet: "second" },
  { path: "secondRoute2", component: SecondRoute2Component, outlet: "second" },
  { path: "thirdRoute1", component: ThirdRoute1Component, outlet: "third" },
];

其中 outlet 属性用于标识目标出口。

激活

现在我们可以在 outlets 中为对应的路由出口指定目标路由,指定为 null 时可关闭路由视图,比如:

<a [routerLink]="[{outlets: { second: 'secondRoute1' }}]">second:secondRoute1</a>
<a [routerLink]="[{outlets: { second: 'secondRoute2' }}]">second:secondRoute2</a>
<a [routerLink]="[{outlets: { second: null }}]">second:null</a>

多重路由之间彼此互不依赖,上面的链接会改变 second 出口的路由视图,但主路由出口和 third 路由出口不受影响。除了动态路径,我们也可以用跳转到对应的 URL 的方法来激活它们。

URL

多重路由在 URL 的表现上由括号包装,比如:http://localhost:4200/route2(second:secondRoute1)。同一模板上有多个路由出口被激活时,URL 中以 // 分隔,父子路由上都有多重路由时就会出现多个括号包装的内容。在使用 URL 激活路由时要注意会不会弄丢其他路由出口的路由视图,正确的代码应该像这样:

this.router.navigateByUrl("/route2(second:secondRoute1)");
this.router.navigateByUrl("/route1/(childRoute1//second:childSecondRoute1)(second:secondRoute1//third:thirdRoute1)");
原文地址:https://www.cnblogs.com/yshenhua/p/14674960.html