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

ag-grid中点击列按钮无法单独禁用对应行另一列按钮

解决ag-grid单行按钮控制同行列按钮禁用的问题

问题根源

  • 公共服务的全局变量会被所有行的Button2共享,导致点击任意行Button1都会禁用所有Button2。
  • 直接修改params.rowData的字段后,没有触发ag-grid的行数据刷新,组件无法感知状态变化。

正确实现步骤

1. 调整按钮渲染组件的状态绑定

让Button2的禁用状态直接绑定到当前行数据的button2字段,替代全局服务变量:

<!-- button-renderer.component.html -->
<button
  *ngIf="params['comp'] == 'label1'"
  mat-flat-button
  color="primary"
  (click)="clickButton1()"
  [disabled]="params.data.button1"
>
  Button1
</button>
<button
  *ngIf="params['comp'] == 'label2'"
  mat-flat-button
  color="primary"
  (click)="clickButton2()"
  [disabled]="params.data.button2"
>
  Button2
</button>

2. 修改Button1点击事件逻辑

点击Button1时更新当前行的button2字段,并通过ag-grid的API触发该行对应单元格的刷新:

// button-renderer.component.ts
clickButton1() {
  console.log('Button 1 is clicked');
  // 更新当前行的button2禁用状态
  this.params.data.button2 = true;
  // 精准刷新当前行的Button2所在列
  this.params.api.refreshCells({
    rowNodes: [this.params.node],
    columns: ['model'], // 对应Button2列的field值
    force: true
  });
  // 执行DB更新调用
}

3. 完善组件的refresh方法

确保组件在ag-grid触发刷新时同步最新的行数据:

// button-renderer.component.ts
refresh(params: ICellRendererParams): boolean {
  this.params = params;
  return true;
}

4. 移除不必要的全局服务依赖

既然不需要全局控制,可删除组件中对CommonService的引用:

// button-renderer.component.ts
// 移除以下代码:
// import { CommonService } from '../common.service';
// constructor(public comSvc: CommonService) {}

关键说明

  • params.data指向当前行的原始数据对象,修改后必须通过refreshCells通知ag-grid更新,否则组件不会重新渲染。
  • refreshCells的参数可精准控制刷新范围,避免不必要的性能损耗。
  • 行数据中的button1、button2字段需与初始数据结构保持一致,确保状态绑定生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:42:49