简体   繁体   中英

Filter one ag-grid based on event from another one

I want to select one row in my first grid grid1 and the event function would then filter my other grid grid2 based on the values found in the selected row. I am using the pure javascript version of the library.

Something like

gridOptions:{
    onRowSelected:my_event_filter_func,
    rowData: [...],
    columnDefs:[...]
}
grid1 = new agGrid.Grid(document.querySelector("#the_place"),gridOptions)

( grid2 is defined the same way based on different data and w/o the event function)

where my_event_filter_func is

my_event_filter_func = function(event) {
    let my_name = event.data.name
    // filter grid2 to show only the rows where the 'name' column matches my_name
}

Any help is appreciated.

I can't give you a line by line answer, and I am assuming that you are able to get your selected rows. But what I can suggest is, first, you create a copy of your the data that is on your grid2.

function copyData() {
  rowData = [];
  gridApi.forEachNode(node => rowData.push(node.data));
  // temp is the copy of your full data in grid2
  temp = [...rowData];
}

Next, on your my_event_filter_func , you can filter out the rows to be shown on grid2, based on the filtered value from grid1.

function my_event_filter_func(event) {
  let my_name = event.data.name

  // get the rows that do not have the matching value
  const rowsToBeRemoved = temp.filter(row => row['name'] !== my_name);

  // remove the rows from grid2 that do not have the matching names
  gridOptions.api.updateRowData({remove: rowsToBeRemoved});

}

The source for the 2 grids is the underlying data for grid1 so it made my life easier. If that is not the case, you do need to save your base data for grid2 somewhere so that you can access it when the event gets triggered.

I ended up declaring my 2 grids as global variables and using the function below as event function :

var onSelectionChanged = function(event) {

let name = grid1.gridOptions.api.getSelectedRows()[0].name; // we know there is only one
let newRowData = grid1.gridOptions.rowData
    .filter(x => x.name===name)
    .map(x => {
            return {
                'name': x.name
                // other fields...
            }
    })
    // this overwrites grid2 data so need to save original data somewhere.
    grid2.gridOptions.api.setRowData(newRowData);
    grid2.gridOptions.api.refreshCells({force:true});
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM