首页 > 解决方案 > 当我使用路由器插座时,如何在子路由中从父路由中创建空组件

问题描述

我有一个父路由,单击时我会显示来自一个子路由的内容,而在子路由中,单击时我会获取不同的数据并router-outlet在父组件的 HTML 中使用。现在我想div根据条件从父 ts 文件中清空子路由中呈现的内容。有任何想法吗?

这是我的代码

// Here is the caller method
openRoleSection(roleId: string) {
    // Here is the condition, and when it is met, I need to empty the div in the parent route
    if (roleId != this.adminServices.serviceRoleId) {
        alert("yes")
    }
    // Here I am calling the parent routes
    this.router.navigateByUrl(`adminpanel/specific-role-section/${roleId}`, { relativeTo: this.activatedRoute })
}
<!-- I need to empty this div from the child route -->
<div *ngIf="isViewAllEmployeesButtonClicked">
    <div *ngFor="let employee of allUsersFromTheSameRole">
        <p>{{ employee }}</p>
    </div>
</div>

标签: angular

解决方案


您可以在导航时将查询参数传递给子路由,并用于填充/取消填充子组件中的特定信息。

有关更多信息,请参阅https://angular.io/guide/router#query-parameters-and-fragments

例如,类似的东西

父母

 const params:{
    roleId: this.adminServices.serviceRoleId
  }
 this.router.navigateByUrl(`adminpanel/specific-role-section/${roleId}` ,  {relativeTo: this.activatedRoute, , queryParams: params})

孩子

constructor(route:activatedRoute){
this.roleId= this.route
      .queryParamMap
      .pipe(map(params => params.get('roleId') || undefined));
}
<div *ngIf="roleId"></div>

推荐阅读