在子路由中设置命名路由器的内容

时间:2017-12-08 20:06:44

标签: angular angular-router router-outlet

在我的应用程序中,我想在两个路由器插座中显示内容,主要路由器和命名路由器。如果我将两个出口都放在根级别上,我可以像这样设置指定出口的内容:

this.router.navigate([{ outlets: { rootSecondary: ['rootSecondaryPath'] } }]);

但是,我希望应用程序的总体布局提供单个路由器插座,并且能够在子路由中使用不同的路由器插座结构。

如果我创建了一个子路由,它也有一个主要和一个命名的插座,我无法设置辅助插座的内容。报告的错误是:

  

无法匹配任何路线。

路线的定义如下:

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 的模板包含主要插座,并且 - 出于测试目的 - 包含指定的辅助插座:

<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'] } }]);
}

如何更改代码以填充路由器插座childSecondary?

1 个答案:

答案 0 :(得分:5)

为了解决这个问题,我需要将relativeTo param设置为当前活动路线的父级:

export class ChildPrimaryComponent {

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

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