Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column index on Cell Click event in ag-grid?

I think of simplifying the click events and instead of attach them on column renderer (I use React), I tried to attach a single onCellClicked event (where I do get all the data for the row) and do a switch for... column. On first column there will be a delete button, on second something else, etc. I do have some colDef and column, but no index for the column. Instead I have a colId, which isn't what I need. I do have a colDef, where column header could be used, but for my case I don't have headers. I can't imagine how they omitted the column index.

like image 618
Paul Pacurar Avatar asked Nov 17 '25 04:11

Paul Pacurar


1 Answers

You can get all columns and find its index based on the field property if you don't provide the colId:

<AgGridReact
  {...}
  onCellClicked={(e) => {
    const field = e.colDef.field;
    const colIndex = e.columnApi
      .getAllColumns()
      ?.findIndex((col) => col.getColDef().field === field);

    console.log(field, colIndex);
  }}
/>

Codesandbox Demo

like image 147
NearHuscarl Avatar answered Nov 18 '25 19:11

NearHuscarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!