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

Angular Material mat-table整行hover效果实现问题求助

Angular Material mat-table 实现整行鼠标悬停背景色

要实现整行的hover效果,你需要把hover事件绑定到表格的行元素(mat-row)上,而不是单个单元格。修改方式如下:

修改模板代码

给mat-row添加一个自定义类,比如table-row:

<table mat-table [dataSource]="dataSource">

  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <!-- 给mat-row添加table-row类 -->
  <tr mat-row class="table-row" *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

修改样式代码

通过行的hover状态,控制该行内所有单元格的背景色:

.table-row:hover mat-cell {
  background: yellow;
}

原理说明

原来的代码只给单个单元格绑定了hover事件,所以只有鼠标指向的单元格变色。现在改为监听整行的hover状态,当鼠标悬停在整行上时,该行内的所有mat-cell都会应用背景色,从而实现整行变色的效果。如果直接设置行的背景色,可能会被Angular Material内置的单元格样式覆盖,所以针对单元格设置更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:03:25