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

使用自定义组件的ag-grid切换窗口后焦点丢失,如何保留原焦点?

AG Grid 窗口切换时保留焦点的解决方案

1. 记录失焦前的焦点状态

在窗口失去焦点时,捕获AG Grid当前的焦点元素信息并存储:

let lastFocusedCell;
let lastFocusedHeader;

// 绑定窗口失焦事件
const handleWindowBlur = () => {
  lastFocusedCell = gridApi.getFocusedCell();
  lastFocusedHeader = gridApi.getFocusedHeader();
};
window.addEventListener('blur', handleWindowBlur);

2. 窗口恢复焦点时重置焦点

监听窗口聚焦事件,根据存储的信息恢复对应元素的焦点:

const handleWindowFocus = () => {
  // 恢复单元格焦点
  if (lastFocusedCell) {
    gridApi.setFocusedCell(lastFocusedCell.rowIndex, lastFocusedCell.column.getId());
    // 针对自定义cellRenderer,手动触发DOM元素焦点
    const cellInstance = gridApi.getCellRendererInstances({
      rowIndex: lastFocusedCell.rowIndex,
      columns: [lastFocusedCell.column.getId()]
    })[0];
    cellInstance?.eGui?.focus();
  }
  // 恢复列头焦点
  else if (lastFocusedHeader) {
    gridApi.setFocusedHeader(lastFocusedHeader.column.getId());
    const headerInstance = gridApi.getHeaderCellRendererInstances({
      columns: [lastFocusedHeader.column.getId()]
    })[0];
    headerInstance?.eGui?.focus();
  }
};
window.addEventListener('focus', handleWindowFocus);

3. 确保自定义组件支持焦点捕获

自定义headerComponent和cellRenderer时,需给组件根元素添加tabindex属性,保证元素可被焦点选中:

<!-- 自定义cellRenderer模板示例 -->
<div class="custom-cell" tabindex="0">{{ params.value }}</div>

<!-- 自定义headerComponent模板示例 -->
<div class="custom-header" tabindex="0">{{ params.displayName }}</div>

4. 清理事件监听避免内存泄漏

在组件销毁阶段,移除窗口事件绑定:

// 组件销毁时执行
window.removeEventListener('blur', handleWindowBlur);
window.removeEventListener('focus', handleWindowFocus);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:29:52