'How to filter selected Rows in AG grid and keep it as selected?

I want to filter my AG grid rows based on checkbox selection and I want to keep them as selected.

I know using below method I can filter selected rows but after filtering the rows are losing its selected state.

gridOptions.api.setRowData(gridOptions.api.getSelectedRows())

I can run gridoptions.api.selectAll() but I have to avoid it as I don't want AG grid selection change event to be triggered.

Any Idea how can I achieve it?



Solution 1:[1]

Use ag-grid filter external to filter columns by hand. In the rowdefintion set the filter for the rows to true. Override the methods isExternalFilterPresent and doesExternalFilterPass from ag-grid in HTML

  <ag-grid-angular
  [columnDefs]="columnDefs"
  [isExternalFilterPresent]="isExternalFilterPresent"
  [doesExternalFilterPass]="doesExternalFilterPass"
  [rowData]="rowData"
  (gridReady)="onGridReady($event)"
></ag-grid-angular>

in .ts define outside of your component (or do it static)

// Used in isExternalFilterPresent() to detect if (external)filter is active or not
let Gobal_filterSelectedDocuments: boolean;

and in your component

onToggleDocumentsFilterClick(event: MatSlideToggleChange) {
    Gobal_filterSelectedDocuments = event.checked;
    // nesseary notification to enable the filter
    this.gridApiObjects.onFilterChanged()
}

isExternalFilterPresent() {
    // Here we have no access to the 'this.' of the component. Use a Global Variable instedt.
    return Gobal_filterSelectedDocuments;
}

doesExternalFilterPass(node) {
    // Show only selected nodes
    return node.isSelected();
}

The biggest issue is that the isExternalFilterPresent() has a differnt scope and the this. is an angular object (gridapi?) not the current component. So i needed a gobal/static variable to work around this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 norca