【问题标题】:Create a child page with multiple parent创建具有多个父级的子页面
【发布时间】:2019-07-25 22:27:56
【问题描述】:

我想在 Angular 应用程序中创建一个导航,我可以在其中从多个“父”页面访问同一个页面,并让导航知道它来自哪个页面。

我在导航中使用routerLinkActive="active"。我有两个页面(收藏夹,所有用户)显示用户列表。用户有一个详细信息页面,您可以使用 users/userId 导航到该页面。

我想做的是,当从“收藏夹”列表中单击用户详细信息链接时,“活动”导航停留在“收藏夹”菜单按钮上,当我从所有用户中点击时,它会停留在所有用户

这就是我当前的路线配置方式

const routes: Routes = [
{
  path: 'favorites',
  component: FavoritesComponent
},
{
  path: 'all',
  component: AllUsersComponent
},
{
  path: 'user/:id',
  component: UserDetailComponent,
}

这就是我的路线当前的配置方式,显然,当我导航到 user/id 页面时,favoritesall 在我的导航栏中都不是“活动的”。

【问题讨论】:

  • 你能提供stackblitz代码示例吗?
  • 一个嵌套的路由器插座应该可以解决这个问题,但是你能更具体地说明你想要完成的事情吗?
  • 一个简单的解决方案是为同一个组件(UserDetailComponent)创建两个单独的子路由,并且这个路由应该作为子路由添加到父路由favoritesall跨度>

标签: angular typescript angular-router


【解决方案1】:

您可以在每个主路由下重复使用相同的组件作为子路由,即favoritesall。这里的关键是定义一个空路由路径,该路径指向该路由的主要组件,然后创建一个将属于主路由的详细路由。您的路线配置应如下所示:

const appRoutes: Routes = [
  {
    path: 'favorites',
    children: [
      {
        path: '',
        component: FavoritesComponent
      },
      {
        path: 'user/:id',
        component: UserDetailComponent,
      }
    ]
  },
  {
    path: 'all',
    children: [
      {
        path: '',
        component: AllUsersComponent
      },
      {
        path: 'user/:id',
        component: UserDetailComponent,
      }
    ]
  },
  {
    path: 'user/:id',
    component: UserDetailComponent,
  },
  { path: '**', redirectTo: "/all" }
];

通过上述配置,favoritesall 链接将按照您的意愿运行。

StackBlitz

【讨论】:

  • 谢谢,这确实是我想要做的。现在,如果UserDetailComponent 有子路由(我们在此页面上有标签),我们必须在所有三个路径中重复子路由还是有更简单的解决方案?
  • 没关系,您的 stackblitz 代码已经回答了这个问题,只需使用 const 来定义 UserDetailComponent 路由。完美,谢谢!
猜你喜欢
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
相关资源
最近更新 更多