用于Menu和SubMenu配置的Angular(Angular 4)RouterLinkActive

时间:2017-07-15 19:15:50

标签: javascript angular typescript angular-routing

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

-------------------------
|   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']),
];

SubMenu链接

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/1A1都处于“有效”状态。但是,当我点击子菜单时,请说2,然后A不再“活跃”,因为它与/A/1匹配(这是有意义的,这就是它与之相关联的内容)。

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

https://embed.plnkr.co/BQKy67J2OfVskmwPbTDl

1 个答案:

答案 0 :(得分:1)

问题在于您的路由以及p的定义。您应该只定义链接中的父组件。否则它只匹配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 },
];

检查edited plunkr