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

Angular Material Table:保持行RouterLink时,如何屏蔽操作列行跳转?

解决Angular mat-table中禁用按钮点击触发行routerLink跳转的问题

你的问题核心是禁用状态下的按钮点击会触发父tr的routerLink跳转,之前在(click)里加$event.stopPropagation()没用,是因为禁用的按钮不会触发click事件,导致阻止冒泡的代码根本没执行。下面是两种不用拆分routerLink到每个td的优化方案:

方案一:给按钮添加mousedown事件阻止冒泡

禁用元素依然会接收mousedown这类底层鼠标事件,在这个事件里阻止冒泡,就能切断事件向tr的传递:

<a mat-raised-button color="primary"
   (click)="activate(row.name, row.eventCount); clicked = true;"
   [disabled]="clicked || row.eventCount > 0"
   (mousedown)="$event.stopPropagation()">Activate</a>

方案二:给操作列的td添加阻止冒泡

如果操作列有多个按钮,直接给整个td加mousedown事件,一次性解决该列所有元素的冒泡问题:

<td mat-cell *matCellDef="let row" class="whitespace-nowrap actions-column"
    (mousedown)="$event.stopPropagation()">
  <a mat-raised-button color="primary"
     (click)="activate(row.name, row.eventCount); clicked = true;"
     [disabled]="clicked || row.eventCount > 0">Activate</a>
  <!-- 后续添加的其他按钮也不需要单独加阻止冒泡 -->
</td>

原理说明

Angular的routerLink是通过监听tr的点击事件来触发跳转的,当点击禁用按钮时,虽然按钮的click事件被浏览器拦截,但mousedown事件依然会向上冒泡到tr,触发跳转。通过在mousedown阶段阻止冒泡,就能让事件无法到达tr,自然不会触发路由跳转。

内容的提问来源于stack exchange,提问作者рüффп

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:52:09