【问题标题】:Angular (Angular 4) RouterLinkActive for Menu and SubMenu configurationAngular (Angular 4) RouterLinkActive 用于菜单和子菜单配置
【发布时间】:2017-07-16 06:19:43
【问题描述】:

我的应用有一个菜单和一个子菜单。当他们点击菜单时,我需要该菜单项和第一个子菜单项处于“活动状态”。

-------------------------
|   A   |   B   |   C   |
-------------------------
| 1 | 2 | 3 | 4 | 5 | 6 |
-------------------------

例如,如果我选择A,那么A1 都是“活动的”。如果我选择B,那么B1 都是“活动的”。 C 也一样。

路线

const subMenuRoutes: Routes = [
  { path: '0', component: ContentComponent }, 
  { path: '1', component: ContentComponent },
  { path: '2', component: ContentComponent },
  { path: '3', component: ContentComponent },
  { path: '4', component: ContentComponent },
  { path: '5', component: ContentComponent },
  { path: '6', component: ContentComponent },
];

const menuRoutes: Routes = [
  { path: 'A', component: SubMenuComponent, children: subMenuRoutes }, 
  { path: 'B', component: SubMenuComponent, children: subMenuRoutes },
  { path: 'C', component: SubMenuComponent, children: subMenuRoutes },
];

菜单链接

links = [
  new Link('A', ['/A', '1']),
  new Link('B', ['/B', '1']),
  new Link('C', ['/C', '1']),
];

子菜单链接

links = [
  new Link('1', ['1']),
  new Link('2', ['2']),
  new Link('3', ['3']),
  new Link('4', ['4']),
  new Link('5', ['5']),
  new Link('6', ['6']),
];

通过此设置,点击A 将转到/A/1,并且A1 都处于“活动状态”。但是当我点击子菜单时,说2,然后A 不再“活跃”,因为它与/A/1 匹配(这是有道理的,这就是它所链接的)。

有没有办法指定我只想匹配A

https://embed.plnkr.co/BQKy67J2OfVskmwPbTDl

【问题讨论】:

  • 您能解释一下您的期望吗?如果你可以创建一个 plunker
  • @Aravind 我添加了一个 plunker。不知道如何嵌入...如果有人可以请编辑。 :)

标签: javascript angular typescript angular-routing


【解决方案1】:

问题在于您的路由和Link 的定义。您应该只定义链接中的父组件。否则它只匹配(A|B|C)/1

links = [
  new Link('A', ['/A']),
  new Link('B', ['/B']),
  new Link('C', ['/C']),
];

然后在您的子路由中使用redirectTo

const subMenuRoutes: Routes = [
  { path: '',  pathMatch: 'full', redirectTo: '1' }
  { path: '0', component: ContentComponent }, 
  { path: '1', component: ContentComponent },
  { path: '2', component: ContentComponent },
  { path: '3', component: ContentComponent },
  { path: '4', component: ContentComponent },
  { path: '5', component: ContentComponent },
  { path: '6', component: ContentComponent },
];

你也不必直接重定向到子路由;重定向到父级,让它处理重定向到子路由。在我看来,这种方式更加模块化。

const menuRoutes: Routes = [
  { path: 'A', component: SubMenuComponent, children: subMenuRoutes }, 
  { path: 'B', component: SubMenuComponent, children: subMenuRoutes },
  { path: 'C', component: SubMenuComponent, children: subMenuRoutes },
  { path: '**', redirectTo: 'A' }
];

检查edited plunkr

【讨论】:

  • @christo8989 作为奖励,您的Link 类可以是interface,因为它内部没有任何行为。
猜你喜欢
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 2019-06-24
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多