You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular侧边栏routerLink双击异常跳转默认路由问题

Angular 侧边栏双击跳转默认路由问题

异常现象

修复Angular应用侧边栏bug时发现如下问题:双击侧边栏菜单项时,页面始终会被重定向到默认路由。例如下方截图所示,点击Financial years菜单项后,页面会跳转至Payment Account路由,所有侧边栏菜单项均使用routerLink指令实现路由跳转。

异常现象截图:
侧边栏异常截图

相关实现代码与配置

侧边栏模板代码

...
<div class="category-children" *ngIf="rlaAcc.isActive">
    <!-- Section Bank Accounts -->
    <div mat-list-item id="item-accounting-transfers" data-intercom-target="Accounting module transfers"
      [routerLink]="['/accounting', property.id, 'transfers']" routerLinkActive="active-child"
      #rlaAccBank="routerLinkActive" class="child-header">
    </div>
    <div class="category-children" *ngIf="rlaAccBank.isActive">
      <div mat-list-item id="item-accounting-transfers" data-intercom-target="Accounting module transfers"
        [routerLink]="['/accounting', property.id, 'transfers', 'currents']" routerLinkActive="active-sub-child"
        class="child-header">

      </div>
      <div mat-list-item id="item-accounting-transfers" data-intercom-target="Accounting module transfers"
        [routerLink]="['/accounting', property.id, 'transfers', 'savings']" routerLinkActive="active-sub-child"
        class="child-header">
 
      </div>
    </div>
...

Accounting 路由配置

export const ACCOUNTING_ROUTES: Route[] = [
   ....
  // 默认跳转规则
  { 
    path: ':propId',
    redirectTo: '/accounting/:propId/transfers/currents',
    pathMatch: 'full', data:{propId:[`:propId`]},
    canActivate: [IsOnboardedGuard]
  },
  { path: ':propId/financial-years', loadChildren: () => import('@xyz/features/accounting/financial-years/main').then(m => m.FinancialYearsHomeModule), canActivate: [IsOnboardedGuard] },
   
 ......
    
];

Financial Year 路由配置

const FINANCIAL_YEAR_ROUTES: Routes = [
  { path: '', component: FinancialYearsHomePage,
    children: [
      { path:'', redirectTo: 'overview', pathMatch: 'full'},
      { path: 'overview', component: FYearsOverviewPage }
    ],
  },
];

测试环境路由日志截图:
路由日志截图

问题原因

这个异常是两个配置逻辑冲突叠加导致的:

  • routerLinkActive指令默认使用前缀匹配规则,而非精确匹配:只要当前URL以routerLink绑定的路径为前缀,就会将isActive状态置为true、加上配置的active样式类。
  • 侧边栏嵌套子菜单的显隐完全依赖routerLinkActive返回的isActive状态控制,比如转账分类下的三级子菜单,显隐条件绑定的是路径/accounting/:propId/transfers对应的rlaAccBank.isActive值。

双击菜单项时,第一次点击触发的路由跳转还未完成,连续触发的路由事件会让前缀匹配逻辑出现误判:/accounting/:propId/financial-years和/accounting/:propId/transfers的路径前缀都是/accounting/:propId/,会直接将rlaAccBank.isActive置为true,本该隐藏的转账三级子菜单瞬间被渲染。子菜单渲染后会立即触发自身绑定的路由指令校验,加上双击触发的第二次路由请求,刚好命中配置的:propId全路径匹配重定向规则,直接跳转到默认的/accounting/:propId/transfers/currents路由,也就是看到的Payment Account页面。

修复方式很简单,给所有父级菜单的routerLinkActive加上[routerLinkActiveOptions]="{exact: true}"配置,强制使用精确匹配规则,就不会出现前缀匹配误判、子菜单意外渲染触发异常跳转的问题。


内容的提问来源于stack exchange,提问作者Philip Mutua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 13:06:31