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

Angular Material UI中点击后如何实现多行单元格颜色持久化

嗨,我来帮你解决这个多行选中后颜色持久化的问题~

原来的代码里selectedRow是单个变量,每次点击都会覆盖之前的值,所以只能保留最后一行的高亮。要实现点击任意行后都保持颜色,我们需要把单个变量改成存储多个选中ID的集合,具体修改如下:

解决多行选中高亮持久化的方案

1. 修改TS代码:用集合存储选中行ID

把单个的selectedRow换成Set(数组也可以,Set的添加/移除操作更便捷),然后在点击方法里切换当前行的选中状态:

// 用Set存储所有选中的行ID,支持快速判断和操作
selectedRows = new Set<number>(); 

showProfile(id: number, row: any) {
  // 切换当前行的选中状态:已选中就移除,未选中就添加
  if (this.selectedRows.has(id)) {
    this.selectedRows.delete(id);
  } else {
    this.selectedRows.add(id);
  }

  // 原有弹窗逻辑保持不变
  this.dialog.open(ViewProfileAdminComponent, { 
    width: '1800px', 
    data: { userId: id, isAdmin: true }, 
  });
}

如果更习惯用数组,也可以这样写:

selectedRows: number[] = [];

showProfile(id: number, row: any) {
  const index = this.selectedRows.indexOf(id);
  if (index > -1) {
    // 已选中,从数组中移除
    this.selectedRows.splice(index, 1);
  } else {
    // 未选中,添加到数组
    this.selectedRows.push(id);
  }

  this.dialog.open(ViewProfileAdminComponent, { 
    width: '1800px', 
    data: { userId: id, isAdmin: true }, 
  });
}

2. 修改HTML的ngClass判断逻辑

原来的判断是对比单个ID,现在要检查当前行ID是否在选中集合/数组里:

对应Set版本的判断:

<ng-container *ngIf="col === 'name'"> 
 <mat-header-cell *matHeaderCellDef> {{ col | titlecase }} </mat-header-cell> 
 <mat-cell *matCellDef=" let row" [ngClass]="{'data-selected': selectedRows.has(row.id)}" > 
 <a mat-button color="primary" (click)="showProfile(row['id'], row)" target="_blank">{{ row[col] }}</a> 
 </mat-cell> 
</ng-container>

对应数组版本的判断:

<ng-container *ngIf="col === 'name'"> 
 <mat-header-cell *matHeaderCellDef> {{ col | titlecase }} </mat-header-cell> 
 <mat-cell *matCellDef=" let row" [ngClass]="{'data-selected': selectedRows.includes(row.id)}" > 
 <a mat-button color="primary" (click)="showProfile(row['id'], row)" target="_blank">{{ row[col] }}</a> 
 </mat-cell> 
</ng-container>

3. CSS代码保持不变

你原来的高亮样式不需要修改,依然生效:

.data-selected { 
 background-color:rgb(34, 110, 34); 
}

这样修改后,每次点击任意行都会切换该行的选中状态,所有选中过的行都会保持高亮,不会因为点击其他行而消失啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:02:42