Angular routerLinkActive 未按预期工作

Angular routerLinkActive not working as expected

我正在做一个相当简单的项目,但这个问题让我很困惑!

除了 routerLinkActive 没有保持激活状态的一个小问题外,我已经设置好路由并正常工作。

我还不能在问题中嵌入图片,所以请按照 link 查看我得到的结果

Routing Results

当我转到:http://localhost:4200/1 the '1' menu item correctly shows as active in the nav bar. If I then go to a child route: http://localhost:4200/1/top100 '1' 菜单仍然设置为活动状态。这正是我希望它工作的方式。

然而,在一个非常相似的设置中,我将“4”菜单项转到:http://localhost:4200/2/A. This correctly shows the '4' in the top nav bar as active and the 'Test A' button as active. But when I go to http://localhost:4200/2/B 然后 'Test B' 按钮正确显示为活动状态,但主导航栏丢失了其活动标志'4'.

下面附上代码片段:

导航栏

<ul class="navbar-nav">
  <li class="nav-item" routerLinkActive="active">
    <a class="nav-link" routerLink="/1">1</a>
  </li>
  <li class="nav-item" routerLinkActive="active">
    <a class="nav-link" [routerLink]="['/notUsed', 'notUsed']">2</a>
  </li>
  <li class="nav-item" routerLinkActive="active">
    <a class="nav-link" [routerLink]="['/notUsed', 'notUsed']">3</a>
  </li>
  <li class="nav-item" routerLinkActive="active">
    <a class="nav-link" [routerLink]="['/2', 'A']">4</a>
  </li>
  <li class="nav-item" routerLinkActive="active">
    <a class="nav-link" routerLink="/notUsed">5</a>
  </li>
</ul>

按钮组

<div class="btn-group-vertical fixedWidthButtonHonour mb-3" role="group" aria-label="Senior Grades">
  <button type="button" class="btn btn btn-outline-danger" [routerLink]="['/2', 'A']" routerLinkActive="active">Test A</button>
  <button type="button" class="btn btn btn-outline-danger" [routerLink]="['/2', 'B']" routerLinkActive="active">Test B</button>
</div>

路线

const appRoutes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: '1', component: Component1 },
  { path: '1/top100/:name', component: ComponentTop100 },
  { path: '2', component: Component2 },
  { path: '2/:viewType', component: Component2 },
  { path: '**', redirectTo: '/', pathMatch: 'full' }
];

我无法弄清楚这两个示例之间的区别。如果有人有任何见解或工作演示可以实现我所追求的目标,那就太好了。

谢谢 大卫

问题是您希望 ['/2', 'A'] 上的 routerLinkActive 在您处于 ['/2', 'B'] 时激活。这不是它的工作原理。您应该在 /2 link 上创建一个 routerLinkActive

如果您不介意总是将 /2 重定向到 /2/A,您可以执行以下操作:

在您的导航栏中:

<li class="nav-item" routerLinkActive="active">
  <a class="nav-link" routerLink="/2">4</a>
</li>

在您的应用程序路线中

const appRoutes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: '1', component: Component1 },
  { path: '1/top100/:name', component: ComponentTop100 },
  { path: '2', redirectTo: '2/A', pathMatch: 'full' },
  { path: '2/:viewType', component: Component2 },
  { path: '**', redirectTo: '/', pathMatch: 'full' }
];

另一种解决方案是根据您当前的路由器路径手动添加 [class.active]