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

为什么Ag-grid可移动列横向滚动时单元格渲染器会重新初始化?

Ag-grid可移动列横向滚动时单元格数值丢失修复方案

核心原因

Ag-grid默认开启列虚拟滚动逻辑,横向滚动时超出可视区域的列DOM会被自动销毁,滚动回可视区域时会重新触发单元格渲染器的agInit生命周期完成初始化。当前代码未将用户在渲染器内修改的数值同步到Ag-grid内部的行数据模型,重新初始化时只会读取原始的初始数据,因此出现数值被重置的问题。

现有代码缺陷

  1. 缺少用户操作后的数据回写逻辑,渲染器内部修改的状态仅保存在组件实例内,未同步到Ag-grid行数据
  2. refresh方法实现不符合要求,返回true告知Ag-grid已完成刷新,但仅更新了formGroup,未同步最新行数据到渲染器内部状态和UI

修复步骤

  • 新增数值变更时的行数据同步逻辑,在渲染器内的表单控件(日期选择器、下拉框等)变更回调中,调用Ag-grid官方API把新值写入行数据模型:
// 示例:日期选择器变更回调
onDateUpdate(newDate: Date): void {
  // 单个字段更新用setDataValue,性能更高
  this.params.node.setDataValue('proposedCompletionDateInFormat', newDate);
  // 多字段批量更新可使用applyTransaction
  // this.params.api.applyTransaction({
  //   update: [{...this.params.data, proposedCompletionDateInFormat: newDate, otherField: newValue}]
  // })
}
  • 修正refresh生命周期实现,每次刷新时同步最新行数据到渲染器内部:
refresh(params?: any): boolean {
  this.params = params;
  this.rowIndex = params.rowIndex;
  this.selectedReason = params.data;
  this.formGroup = params.context.formGroup;
  // 同步最新行数据到UI组件
  if (params.data.proposedCompletionDateInFormat) {
    this.calender.selectedDateTime.startDate = new Date(params.data.proposedCompletionDateInFormat);
  } else {
    this.calender.selectedDateTime = null;
  }
  this.disableField = params.data.taskProgressState === "COMPLETED";
  return true;
}
  • 若业务场景下列总数量不超过50列,可直接在Ag-grid配置项中关闭列虚拟滚动,从根源避免列DOM被频繁销毁重建:
// gridOptions中添加配置
const gridOptions = {
  // 其他配置...
  suppressColumnVirtualisation: true
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:27:00