简体   繁体   中英

Save column header filter in ag-grid in angular

I am working on an existing application in which they have used ag-grid library for angular for most of the grids that they have in their application. Now the ag-grid gives the functionality to filter the grid based on a column value by using the filter option in the column header. I am giving a link to that https://www.ag-grid.com/angular-data-grid/filtering-overview/ . I wanted to implement a feature in which we can save the filter keyword that the user is searching for and when he comes back to the same grid the previous filter is already applied. for example https://plnkr.co/edit/?p=preview&preview here we can pick athlete and filter that by going to the column and searching a value so what I want is that if I search 'abc' I should be able to preserve that. is there a way to do that ? I am giving the colDef for the link above

this.columnDefs = [
      { field: 'athlete' },
      {
        field: 'age',
        filter: 'agNumberColumnFilter',
        maxWidth: 100,
      },
      {
        field: 'date',
        filter: 'agDateColumnFilter',
        filterParams: filterParams,
      },
      {
        field: 'total',
        filter: false,
      },
    ];
    this.defaultColDef = {
      flex: 1,
      minWidth: 150,
      filter: true,
    };
  }

Any kind of help is appreciated, thanks :)

You can save the filter applied by using the Grid Event onFilterChanged . Inside here you can get the filterModel by calling api.getFilterModel() . In the plunkr below we are showcasing this by saving the filter model to local storage and restoring it by applying it inside the Grid Event onFirstDataRendered


  onFilterChanged(params) {
    const filterModel = params.api.getFilterModel();
    localStorage.setItem('filterModel', JSON.stringify(filterModel));
  }

  onFirstDataRendered(params) {
    const filterModel = JSON.parse(localStorage.getItem('filterModel'));
    if (filterModel) {
      params.api.setFilterModel(filterModel);
    }
  }

See this implemented in the following plunkr

You may also find the following documentation pages relevant:

Saving and Restoring Filter Models

Grid Events

To apply existing filters to ag-grid, it can be done using by setting up filterModel on gridApi.

    gridApi.getFilterInstance("fieldName").setModel({
        "filterType":"equals", //type of filter condition
        "type":"text", //Type of column [text/number/date]
        "filter":"value" //Value need to be applied as filter.
     })

Similarly onFilterChanged event you can capture changes and apply filter dynamically.

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