您可以在父路由器出口中显示子路由吗?

时间:2018-06-20 10:17:19

标签: angular-routing angular6 router-outlet

主要问题:是否有办法显示到父路由器出口的子路由?

请参见Angular.io路由器指南中的示例。

主干代码段:

  const appRoutes: Routes = [
      ...
      {
        path: 'admin',
        loadChildren: 'app/admin/admin.module#AdminModule',
        canLoad: [AuthGuard]
      },
      {
        path: 'crisis-center',
        loadChildren: 'app/crisis-center/crisis-center.module#CrisisCenterModule',
        data: { preload: true }
      },
      ....
    ];

主要组件代码段:

@Component({
  selector: 'app-root',
  template: `
    <h1 class="title">Angular Router</h1>
    <nav>
      <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
      <a routerLink="/superheroes" routerLinkActive="active">Heroes</a>
      <a routerLink="/admin" routerLinkActive="active">Admin</a>
      ...
    </nav>
    <router-outlet></router-outlet>
  `
})

CrisisCenter路由摘要:

const crisisCenterRoutes: Routes = [
  {
    path: '',
    component: CrisisCenterComponent,
    children: [
      {
        path: '',
        component: CrisisListComponent,
        children: [
          {
            path: ':id',
            component: CrisisDetailComponent,
            ...
          },
          {
            path: '',
            component: CrisisCenterHomeComponent
          }
        ]
      }
    ]
  }
];

CrisesListComponent代码段:

@Component({
  template: `
    <ul class="items">
      <li *ngFor="let crisis of crises$ | async"
        [class.selected]="crisis.id === selectedId">
        <a [routerLink]="[crisis.id]">
          <span class="badge">{{ crisis.id }}</span>{{ crisis.name }}
        </a>
      </li>
    </ul>

    <router-outlet></router-outlet>
  `
})

CrisisDetailComponent代码段:

@Component({
  template: `
  <div *ngIf="crisis">
    <h3>"{{ editName }}"</h3>
    ...
  </div>
  `
})

此路由器的输出是这样:

enter image description here

所以。我要说的是,当您单击“龙燃烧的城市” 时,为什么不将其显示在CrisesListComponent级别上,而不是将其显示在下面?

我能想到的就是在 CrisesListComponent 中使用 * ngIf

@Component({
  template: `
    <ul class="items" *ngIf="a list is selected hide this!!!">
      <li *ngFor="let crisis of crises$ | async"
        [class.selected]="crisis.id === selectedId">
        <a [routerLink]="[crisis.id]">
          <span class="badge">{{ crisis.id }}</span>{{ crisis.name }}
        </a>
      </li>
    </ul>

    <router-outlet></router-outlet>
  `
})

是否要将子路由器设置为此父路由出口上的此显示?

谢谢。我希望我把问题弄清楚。

1 个答案:

答案 0 :(得分:0)

我认为您可以通过将名称添加到<router-outlet>选择器并将具有该名称的插座属性添加到子路由来实现。 HTML:

<router-outlet name="test"></router-outlet>

儿童路线模块:

path: '',
component: CrisisCenterComponent,
outlet: "test"

尝试一下,这个孩子的嵌套路线可能会遇到一些问题。