在子路由中设置具有名称的router-outlet的内容

5
在我的应用程序中,我想在两个路由出口中显示内容,一个是主要的,另一个是命名的。如果我将这两个出口放在根级别,我可以像这样设置命名出口的内容:
this.router.navigate([{ outlets: { rootSecondary: ['rootSecondaryPath'] } }]);

然而,我希望应用的通用布局提供单个router-outlet,并能够在子路由中使用不同的router-outlet结构。
如果我创建一个具有主要和命名outlet的子路由,我无法设置次要outlet的内容。 报告的错误是:
“无法匹配任何路由。”
这些路由定义如下:
const appRoutes: Routes = [
  { path: '', component: RootPrimaryComponent },
  { path: 'rootSecondaryPath', component: RootSecondaryComponent, outlet: 'rootSecondary' },
  {
    path: 'child', component: ChildComponent, children:
      [
        { path: '', component: ChildPrimaryComponent },
        { path: 'childSecondaryPath', component: ChildSecondaryComponent, outlet: 'childSecondary' },
      ]
  },
];
const appRouting = RouterModule.forRoot(appRoutes);

app.component.html的模板包含一个主要输出口和一个命名为“secondary”的辅助输出口,用于测试目的:

<router-outlet></router-outlet>
<div style="border: solid 1px green">
  <router-outlet name="rootSecondary"></router-outlet>
</div>

上述代码从一个按钮调用并设置了rootSecondary出口,没有任何问题。

模板child.component.html定义了两个出口,这些出口被放置在根主出口内:

<router-outlet></router-outlet>
<div style="border:solid 1px red">
  <router-outlet name="childSecondary"></router-outlet>
</div>

child.primary.component.html 包含一个按钮,调用代码来设置次要出口:

<div>
  child-primary works!
  <button (click)="setChildSecondary()">Set child secondary</button>
</div>

当点击时,将运行以下代码:
setChildSecondary() {
  this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }]);
}

我需要修改代码以便填充router-outlet的子元素childSecondary?

1个回答

6
为了解决这个问题,我需要将relativeTo参数设置为当前活动路由的父级:
export class ChildPrimaryComponent {

  constructor(private readonly router: Router,
    private readonly route: ActivatedRoute) { }

  setChildSecondary() {
    this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }],
      { relativeTo: this.route.parent });
  }
}

干得好!这个问题在我找到你的解决方案前浪费了我一个小时。谢谢你。 - Edward Liang
它在最新的Angular中工作吗? - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接