如何以角度加载命名路由器插座

时间:2021-05-14 19:59:10

标签: angular router-outlet

以下是我的设置。

app.component.html

<p>App Component works!</p>
<router-outlet></router-outlet>

activity.component.html

<p>Activity Component Works!!<p>
<div> There are some other header controls present here, this HTML should render by default</div>
<router-outlet name="activity_router_outlet"></router-outlet>

childa.component.html

<p>ChildA Component Works!!<p>

childb.component.html

<p>ChildB Component Works!!<p>

app-routing.module.ts

{ 
    path: 'activity', 
    component: ActivityComponent,
    canActivate: [AuthenticateGuard],
    loadChildren: () => import('./activity/activity.module').then(m => m.ActivityModule) 
}

activity-routing.module.ts

{
    path: 'activity/childa',
    component: ChildAComponent,
    outlet: 'activity_router_outlet'
},
{
    path: 'activity/childb',
    component: ChildBComponent,
    outlet: 'activity_router_outlet'
}

当我访问以下路线ChildA
http://localhost:4200/activity/childa
以下是我期望的输出

App Component works! 
Activity Component Works!! 
There are some other header controls present here, this HTML should render by default
**ChildA** Component Works!!

当我访问以下路线ChildB
http://localhost:4200/activity/childb
以下是我期望的输出

App Component works! 
Activity Component Works!! 
There are some other header controls present here, this HTML should render by default
**ChildB** Component Works!!

我收到以下错误。什么我不写。请帮忙

<块引用>

无法匹配任何路由。网址段:'activity/childa'

######################################### ########################### ###########################添加更多信息############## ############ ############################################ #########################

Here is my requirement

我对路线有一些限制,因此路线必须与我在上图中描绘的完全相同。

目前这是我的activity.component.html的样子

<p>Activity Component Works!!<p>
<app-activityheader></app-activityheader>
<app-childa *ngIf="_router.has.childa.in.the.url"></app-childa>
<app-childb *ngIf="_router.has.childb.in.the.url"></app-childb>
<app-childc *ngIf="_router.has.childc.in.the.url"></app-childc>

并且路由配置如下,对于任何 URL(如图所示),我正在加载主 AcitivityComponent,然后使用 *ngIf 处理 HTML 中的 ChildComponent 加载。

{
    path: 'activity/childa', component: ActivityComponent,
},
{
    path: 'activity/childb', component: ActivityComponent,
},
{
    path: 'activity/childc', component: ActivityComponent,
}

它的缺点是,每次访问该 URL 时,都会重新加载所有组件。但是我希望 ActivityComponent 和 ActivityHeaderComponent 只加载一次,并且只根据需要重新加载子组件。 实现此功能的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

您需要检查您的路由。以下步骤将解决您的问题

将您的路由配置更改为

     {
        path: 'childa',
        component: ChildaComponent,
        outlet: 'activity_router_outlet'
      },
      {
        path: 'childb',
        component: ChildbComponent,
        outlet: 'activity_router_outlet'
      }

我只是删除了“活动”前缀

现在在您的链接中,我们可以用

定义它们
<a [routerLink]="['/activity',{ outlets: {primary: null, activity_router_outlet: 'childa'}}]">/activity/childA</a> <br />
<a [routerLink]="['/activity',{ outlets: {primary: null, activity_router_outlet: 'childb'}}]">/activity/childB</a>

Demo Here