ag-grid: Using Javascript, find the row id for a given data

5.3k Views Asked by At

I have a list of employees and I want to find the “id” of the row where firstName=Bob which is unique. In other words, I know the firstName supplied as “Bob” and now, I just need to find the row id using Javascript for ag-grid.

According to the documentation https://www.ag-grid.com/javascript-grid/accessing-data/ and I see that the rowNode can be got by using

getRowNodeId: data => data.id,

But I am just unable to to send the parameters (Bob), so that ag-grid finds and puts the id in some assigned variable. I think foreachloop is unnecessary to iterate each and every row, in case if the dataset is too big, then it will be an overhead.

I have the index.html file and a cellRenderer script as shown below. When the circle icon is clicked, I get the row Id correctly, but I am unable to retrieve the firstName, lastName etc.


I tried in two ways (i) writing the evenlistener inside the cellRenderer class, but most convenient for is to take this event listener as a function out of the cell Renderer file. (ii) So, I added a function called getAlert() which you can see as commented. Nothing works for me.

index.html

<div id="myGrid" style="height: 800px; width:100%;" class="ag-theme-alpine"></div>
    <script>
    var colSpan = function (params) {
      return params.data === 2 ? 3 : 1;
    };
    const columnDefs = [
      { headerName:'FIRST NAME',field: "firstName", width:100, cellClass: 'my-class', colSpan: colSpan,},
      { headerName:'LAST NAME',field: "lastName", cellClass: 'my-class', flex: 6,},
      { headerName:'DESIGNATION (%)',field: "designation", cellClass: 'my-class', flex: 1,},
      { headerName:'INFO', field: "row_id",flex: 2, cellRenderer: 'infoCellRenderer'},
      { headerName:'COMMAND',field: "action",flex: 2,},
    ];

    // let the grid know which columns and what data to use
    const gridOptions = {
        defaultColDef: {
            resizable: true,
        },
      columnDefs: columnDefs,
      getRowNodeId: data => data.id,
      onGridReady: event => console.log('The grid is now ready'),

      components:{
        infoCellRenderer: InfoCellRenderer,
      },
    };
    /*function getAlert(params)
    {
      
      console.log(params.node.firstName+","+params.firstName+","+params.value);
      
    }*/
    document.addEventListener('DOMContentLoaded', function () {
      var gridDiv = document.querySelector('#myGrid');
      new agGrid.Grid(gridDiv, gridOptions);
      //gridOptions.api.refreshView();
      agGrid
        .simpleHttpRequest({
          url: 'XXXXXXX',
        })
        .then((data) => {
          gridOptions.api.setRowData(data);
        });
    });
    </script>

cellRenderer class

class InfoCellRenderer {
      constructor() {}
      // gets called once before the renderer is used
      init(params) {
        // create the cell
        this.eGui = document.createElement('div');
        this.eGui.innerHTML = '<a href="#" class="circle"><i class="fas fa-info-circle"></i></a>';

        // get references to the elements we want
        this.circleValue = this.eGui.querySelector('.circle');

        // add event listener to button
        this.cellValue = this.getValueToDisplay(params);

        //this.eventListener = () => getAlert('${params}');
        this.eventListener = () => console.log(`${params.node.id},${params.node.firstName},${params.node.row_id}`);
        this.circleValue.addEventListener('click', this.eventListener);
      }

      getGui() {
        return this.eGui;
      }

      // gets called whenever the cell refreshes
      refresh() {
        // set value into cell again
        this.cellValue = this.getValueToDisplay(params);
        //this.eValue.innerHTML = this.cellValue;

        // return true to tell the grid we refreshed successfully
        return true;
      }

      // gets called when the cell is removed from the grid
      destroy() {
        // do cleanup, remove event listener from button
        if(this.circleValue) {
          // check that the button element exists as destroy() can be called before getGui()
          this.circleValue.removeEventListener('click', this.eventListener);
        }
      }

      getValueToDisplay(params) {
        return params.valueFormatted ? params.valueFormatted : params.value;
      }
    }
2

There are 2 best solutions below

4
Mazdak On

if firstName is unique you can do as followed:

this.gridOptions.getRowNodeId = data => {
      return data.firstName;
};

this code tells ag-grid to use firstName as its internal row Id. so you can easily get the row by:

const node = this.gridApi.getRowNode('Bob');

see link (note // ********* comments ) for full example

0
nmz787 On
gridOptions.api.getModel().forEachNode(
    function(rowNode, index){
        if (rowNode.data.firstName == "Bob") {
            row_index = index;
            row = gridOptions.api.getModel().rowsToDisplay[row_index];
            data_dict = row.data;
            // do something with your row data, data_dict
        }
    }
);