Angular (Angular 4) 用于菜单和子菜单配置的 RouterLinkActive

Angular (Angular 4) RouterLinkActive for Menu and SubMenu configuration

我的应用有一个菜单和一个子菜单。当他们单击菜单时,我需要该菜单项和第一个子菜单项为 "active"。

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

例如,如果我 select A 那么 A1 都是 "active"。如果我 select B 那么 B1 都是 "active"。 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 都是 "active"。但是当我单击子菜单时,说 2,然后 A 不再是 "active",因为它与 /A/1 匹配(这是有道理的,这就是它所链接的内容)。

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

https://embed.plnkr.co/BQKy67J2OfVskmwPbTDl

问题出在您的路由和 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