如何给ag-grid中的header列添加点击事件?

How to add click event to column header in ag-grid?

我需要在单击 header 列时选择整列。我无法为此找到任何解决方案,因为 ag-grid 中的列没有 'click' 事件。我能找到的唯一事件是 'sort''pin' 列。 我还希望在单击时获得列数据,以便我可以根据选择的列执行其他任务。附上屏幕截图以便更好地理解。

通过从所有具有 class 名称的 div 中提取 col-id 属性解决了这个问题 'ag-header-cell'.

this.colElements = Array.from(
  document.getElementsByClassName('ag-header-cell') as HTMLCollectionOf<
    HTMLElement
  >
);

然后在找到的每个项目上添加点击事件侦听器。当我们点击列 header.

时,这将为我们提供 col-id 属性
this.colElements.forEach((elem, index) => {
  elem.addEventListener('click', () => {
    attribute = elem.getAttribute('col-id');
    //you can add you custom styling based on selected index here
  });
});

接下来在 'columnDefs' 数组中我们添加自定义 'cellStyle' 通过基于 col-id 我们提取了。

columnDefs: [
      {
        headerName: 'State',
        field: 'dynamic',
        cellStyle: (params) => {
          if (params.colDef.field === this.selectedColId) {
            return { color: '#001D6D', backgroundColor: '#F3F7FF' };
          }
          return null;
        },
      },
    ],

最后,在事件侦听器的每个点击事件上,我们添加 'redrawRow' 函数。

columnSelected(colId) {
  this.gridOptions.api.redrawRows();
}