Angular 4:禁用祖父母的html模板

时间:2018-01-20 06:30:10

标签: angular angular-ui-router

我有一个包含以下路线的组件

    {
         path: ':id', component: ProjectDetailsComponent,
         children: [
           {path: '', redirectTo: 'gathering', pathMatch: 'full'},
           {path: 'gathering', component: DeviceComponent},
           {
                path: 'mapping/:migWindowId', component: MigrationWindowComponent,
                children: [
                  {path: '', redirectTo: 'premigration', pathMatch: 'full'},
                  {path: 'premigration', component: PreMigrationComponent,
                       canActivate: [AuthGuard]}
                ]
           }
        ]
     }

因此,PremigrationComponent是ProjectDetailsComponent和MigrationWindowComponent的孙子,位于中间。

ProjectDetailsComponent的模板就像这样

<div class="ui-step ui-step--alt active ui-step-change">
 <div class="step__icon step__icon--small" [routerLink]="['gathering']">1</div>
 <div class="step__label">Data Gathering</div>
</div>
<router-outlet></router-outlet>

MigrationWindowComponent的模板是

<div class="ui-step ui-step--alt active ui-step-change">
    <div class="step__icon step__icon--small" [routerLink]="['premigration']">1</div>
    <div class="step__label">Pre Migration</div>
</div><router-outlet></router-outlet>

我正在尝试的是,我想在加载孙子模板时将模板隐藏在祖父母的<router-outlet>标签上方。我尝试使用事件发射器通过通知父级然后通知其父级来实现此目的。但我觉得这不是一种优雅的方式。对此有什么优化吗?

1 个答案:

答案 0 :(得分:0)

第一个选项:

如果你遇到这个问题,孩子应该是兄弟姐妹:

[
    {
         path: ':id', component: ProjectDetailsComponent,
         children: [
           {path: '', redirectTo: 'gathering', pathMatch: 'full'},
           {path: 'gathering', component: DeviceComponent},
        ]
     },
     {
         path: ':id/mapping/:migWindowId', component: MigrationWindowComponent,
         children: [
           {path: '', redirectTo: 'premigration', pathMatch: 'full'},
           {path: 'premigration', component: PreMigrationComponent, canActivate: [AuthGuard]}
         ]
     }
]

第二个选项

如果你不想要#1,你可以根据当前网址从DOM中删除父母的组件(查看Router类):

<div class="ui-step ui-step--alt active ui-step-change"
     *ngIf="noChildrenActivated()">
   <div class="step__icon step__icon--small" [routerLink]="['gathering']">1</div>
   <div class="step__label">Data Gathering</div>
</div>
<router-outlet></router-outlet>

ProjectDetailsComponent

constructor(private router: Router) {}

public noChildrenActivated()
{
    const currentUrl =  this.router.routerState.snapshot.url;
    const urlMatchesChildren = new RegExp('/.*/mapping/.*/premigration').test(currentUrl);
    return !urlMatchesChildren;
}

由于模板中使用了noChildrenActivated()函数,Angular会在每次更改值(经常)时执行它,包括从一个页面切换到另一个页面时。