How to retrieve the column index in ag-grid?
Asked Answered
C

6

11

In ag-grid, when I want to retrieve the row index I use:

params.node.id

However, I couldn't find a way to do the same for columns. All that I found is retrieve the columnId which refers to the field variable in the column definition.
I.e: If this is the column definition:

 {
   headerName: "checkButton 2",
   field: "checkbuttonTwo",
   cellRenderer: "checkButtonComponent",
   width: 150
 }

This:

params.column.getId()  

Would return:

 checkbuttonTwo

So my question is:
Is there any way to retrieve the column index? For example: For the second column I would have 2 and so on and so forth.
Thank you

Concertante answered 25/5, 2019 at 13:21 Comment(0)
I
9

I wrote a helper function in TypeScript for getting the column index by col id.

function getColumnIndexByColId(api: ColumnApi, colId: string): number {
    return api.getAllColumns().findIndex(col => col.getColId() === colId);
}
Incestuous answered 24/9, 2020 at 14:48 Comment(1)
This doesn't work for me. I use the gridColumnApi and call its getAllGridColumns() method.Allemande
F
1

There is no direct way to get the column index, however you can use the getAllColumns() method on Column API to get all columns and then find the index of your column from that array.

More info on Column API here

Florrieflorry answered 25/5, 2019 at 13:45 Comment(2)
No, I actually found a trick to solve this. will post the answer later onConcertante
@AhmedGhrib could you share your solution with everyone?Mcinerney
B
1

If you use GridApi to retrieve columnDefs like this:

api.getColumnDefs();

returned array has the same order as displayed data on the table.

Billhead answered 1/3, 2022 at 14:57 Comment(0)
W
0

Looks like Column API are deprecated as of v.31 in favor of Grid API.

So, using Grid API this is what works for me, thanks to @konuralpt's answer :

colIndex = params.api.getColumnDefs().findIndex(col => col.field === params.column.colId);

... where params.column.colId would return "checkbuttonTwo" in OP's example. (The OP's params.column.getId() works, too).

Weirdo answered 22/8, 2024 at 16:50 Comment(0)
F
-1

You can get the column headerName by running this function:

function CustomTooltip() {}

CustomTooltip.prototype.init = function(params) {
  var headerName = params.colDef.headerName;
}
Frisket answered 7/6, 2020 at 21:19 Comment(0)
C
-5

For each column, You can define a unique id this way:

{
          headerName: "Axa premises",
          field: "axPr",
          width: 150,
          id:0,
          cellRenderer:'iasaCheckboxRendererComponent'
            }

And you can access it in this manner:

this.params.column.colDef.id
Concertante answered 26/5, 2019 at 9:38 Comment(1)
You forced client to use number as id, This column could be reordered, what then?Mailbag

© 2022 - 2025 — McMap. All rights reserved.