Search code examples
filterag-gridag-grid-angular

Ag Grid how to set filter server side from code


I have Ag grid with Angular in my project and I added filters to the grid.

 function ServerSideDatasource(server, projectListComponent) {
      return {
    
        getRows: function (params) {
          
          var response = server.getData(params.request).then((res) => {
...

When I choose sample filters in columns headers the params.request.filterModel returns json (two filter were choosen):

"{
"ProjectID":{"filterType":"number","type":"equals","filter":10,"filterTo":null},
"ProjectName":{"filterType":"text","type":"equals","filter":"P"}
}"

And it works. But I want to assign above json to filter of Ag grid when view is loaded at the start? I want to set filters at the begin by assigning json with predefined values.

I try to in this way, but it doesn't work:

var jsonText = "{ \"ProjectID\": { \"filterType\": \"number\", \"type\": \"equals\", \"filter\": 10, \"filterTo\": null },"
      + "\"ProjectName\": { \"filterType\": \"text\", \"type\": \"equals\", \"filter\": \"P\" }"
      + "} ";
    var jsonFilter = JSON.parse(jsonText);

    this.gridApi.rowModel.filterManager.allFilters = jsonFilter;

Solution

  • You can use setModel method for filter

        let filterComponent = this.gridApi.getFilterInstance('ProjectID');    
        filterComponent.setModel({    
              type: "equals",    
              filter: 10    
            });    
       this.gridApi.onFilterChanged();
    

    And then set the other field filter in the same way.