组件未加载到路由器出口

时间:2019-04-29 12:58:12

标签: angular angular-router router-outlet

何时

<router-outlet (activate)="onActivate($event)"></router-outlet>

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

位于同一模板 app.component.html 中,单击“建筑物详细信息”按钮会将 BuildingDetailsComponent 加载到 buildingDetails路由器出口

但是在 app.component.html 中注释掉 buildingDetails路由器出口并在 sidenavigation中注释 buildingDetails路由器出口时.component.html ,BuildingDetailsComponent将不会加载到“建筑物详细信息”按钮上的 buildingDetails路由器出口中。

app.component.html:

<router-outlet (activate)="onActivate($event)"></router-outlet>
<router-outlet name="buildingDetails"></router-outlet>

sidenavigation.component.html:

<p>
  sidenavigation works!
</p>
<button (click)="openBuildingDetails()">
  Building Details
</button>
<hr>
<!--<router-outlet name="buildingDetails"></router-outlet>--> when moving the router outlet here, loading BuildingDetails Component on openBuildingDetails() button click is not working anymore

sidenavigation.component.ts:

public openBuildingDetails() { this.router.navigate([{ outlets: { buildingDetails: "feature-component" } }]); }

app-routing-module:

const appRoutes: Routes = [
{
    path: "",
    component: SidenavigationComponent,
    pathMatch: "full"
},
{
    path: "feature-component",
    loadChildren: "./modules/building/building.module#BuildingModule",
    outlet: "buildingDetails"
}];

@NgModule({
imports: [
    CommonModule,
    RouterModule.forRoot(
        appRoutes,
        {
            enableTracing: true
        }
    )
],
exports: [
    RouterModule
]})

building-routing-module:

const routes: Routes = [
{
    path: "",
    component: BuildingDetailsComponent
}];

@NgModule({
imports: [
    RouterModule.forChild(routes)
],
exports: [
    RouterModule
]})

有人知道为什么以及如何解决吗?

我为每种情况添加了一个代码示例。这两个示例之间的唯一区别是命名路由器出口的位置。第一个正在工作(名为router-outlet在app.component.html中)。第二个不起作用(在sidenavigation.html中名为router-outlet)。

期望的行为:当命名路由器出口与第一个未命名路由器出口位于不同的位置时,也应加载BuildingDetails组件。

问题:将已命名的路由器出口移动到与未命名的路由器出口不同的模板中时,在openBuildingDetails()按钮上单击后,BuildDetails组件不再加载。

工作:https://stackblitz.com/github/stonedraider/router-outlets

不起作用:https://stackblitz.com/github/stonedraider/not-working-router-outlets

1 个答案:

答案 0 :(得分:0)

您必须按如下所示在app.component.html中添加侧面导航选择器,并删除父路由器出口,因为在加载组件时父路由器出口冲突。

<app-sidenavigation></app-sidenavigation>

现在侧面导航组件将加载建筑组件。

请参考以下答案链接以加载具有延迟加载的子项:

Link