关于angular:组件未加载到路由器outlets中

Component not loaded into router-outlet

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

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

在同一个模板 app.component.html 中,点击 BuildingDetails 按钮会将 BuildingDetailsComponent 加载到 buildingDetails 路由器出口中。

但是当注释掉 app.component.html 中的 buildingDetails router-outlet 并在 sidenavigation.component.html 中注释 buildingDetails router-outlet 时,BuildingDetailsComponent 将不再加载到 BuildingDetails 路由器出口中的 BuildingDetails 按钮单击。

app.component.html:

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

sidenavigation.component.html:

1
2
3
4
5
6
7
8
<p><center>[wp_ad_camp_2]</center></p><p>
  sidenavigation works!
</p>
<button (click)="openBuildingDetails()">
  Building Details
</button>

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

应用程序路由模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
]})

构建路由模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
const routes: Routes = [
{
    path:"",
    component: BuildingDetailsComponent
}];

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

有人知道为什么以及如何解决这个问题吗?

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

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

问题:当将命名的路由器outlets移动到与未命名的路由器outlets不同的模板时,BuildingDetails 组件不再在 openBuildingDetails() 按钮单击时加载。

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

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


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

1
</app-sidenavigation>

现在侧边导航组件加载构建组件。

或者参考下面的答案链接来加载延迟加载的孩子:

链接