2

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;
      }
    }
Jay
  • 744
  • 4
  • 14
  • 30
  • you said that you need the nodeId of row with `firstName = 'Bob'`, so you considered 'Bob' to be unique. if yes, you can use `firstName` in `getRowNodeId` and easily get the row in the fastest way. if not, you may have a list of data with the name 'Bob' so use filter or iterate with `forEachNode` . – Mazdak Aug 10 '21 at 19:32
  • Yes it is unique, I have edited the question. Do you mean like this getRowNodeId(“Bob”): data =>data.id. But getRowNodeId is defined inside gridOptions. I am still not understanding you. – Jay Aug 11 '21 at 05:47

2 Answers2

1

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

Mazdak
  • 650
  • 5
  • 13
  • I have actually defined it like this const gridOptions = { getRowNodeId: data => data.firstName, // other grid options ... } //and I call a function outside of gridOptions, like this function getAlert(){ const node = gridApi.getRowNode('Bob'); alert(node); //Using this.gridApi throws error } This also does not work – Jay Aug 11 '21 at 06:26
  • [https://www.ag-grid.com/javascript-grid/accessing-data/#accessing-row-node-api-methods](this is the right way) but there are many problems that may raise errors, like gridApi is not ready (it will be available after `onGridReady(event)`) also grid node is a complex object so replace `alert(node)` with `console.log(node)`. consider sharing a demo if the problem remains. – Mazdak Aug 11 '21 at 06:40
  • I have just explained it with code. Any help would be highly appreciable. – Jay Aug 11 '21 at 07:53
  • My question is, if I can somehow send the row_id or just the id as parameter, I should be able to get the firstName. The click event is just a test case, not necessary that I have to click and get the rowId. Imagine, as if I know the Row Id (say) 55. By passing this rowId (any row id), I want to get the firstName of that row. – Jay Aug 11 '21 at 07:59
0
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
        }
    }
);
nmz787
  • 1,960
  • 1
  • 21
  • 35