Search code examples
angularag-gridag-grid-angular

Use custom filter for objects in ag-grid


I have an ag-grid table and I am passing some objects as data. I want to add some custom filters. Below I have a very simplified version of my problem.

I have an interface VersionInfo which represent the object I am passing to the grid.

export interface VersionInfo {
    version: number;
   // more fields here...
}

Then I specify the schema of the grid and add some data:

columnDefs = [
    {
      headerName: 'Version', 
      field: 'version', 
      filter: 'agNumberColumnFilter',
      comparator: (a, b) => b.version - a.version,
      cellRenderer: (params: ICellRendererParams) => {
        return `Custom rendering ${params.data.version.version}`;
      }
    }
];

rowData = [
    { version: {version: 3} },
    { version: {version: 5} },
    { version: {version: 8} }
];

The HTML looks like this:

<ag-grid-angular 
    style="width: 500px; height: 200px;" 
    class="ag-theme-alpine"
    [rowData]="rowData" 
    [columnDefs]="columnDefs">
</ag-grid-angular>

Everything is working fine excepet for the comparator. I would assume that it would sort the table in reverse order but nothing is happening instead, I just get the table as specified in rowData and as soon something is written into the filter field all entries are filtered. As mentioned before, this is a simplified version, but the problem is the same.


Solution

  • everything is fine in your code but missing only small detail, as follows:

    in your construction, set the grid sortable with DefaultColDef object like this:

    this.defaultColDef = {
      sortable: true,
    };
    

    Edited: Add this part in your column definition:

    ...
    headerName: 'version',
    valueGetter: (params: any) => {
      return 'Custom rendering ' + params.data.version.version;
    },
    ...
    

    Here the solution Plnkr link based on your code:

    I hope it solves your problem. If not, please let me know.