How to make sorting key insensitive in ag-grid?

2020-02-14 07:41发布

问题:

I am working in some grids and I notice that the sorting on all of them is key sensitive is there any way to change that. This is a part of my code.

 columnDefs = [
{
  headerName: 'Id', field: 'id', sort: 'asc', sortable: true, filter: true,
  checkboxSelection: true, resizable: true,
},
{
  headerName: 'Name', field: 'name', sortable: true, filter: true,
  checkboxSelection: false, editable: true, resizable: true,
},
{
  headerName: 'Description', field: 'description', sortable: true, filter: true,
  checkboxSelection: false, editable: true, resizable: true,
},
  ];

Thank you for any possible given help.

This is how i have implement the solution by ##wentjun##:

  constructor(private dialog: MatDialog, private adminService: AdminService) {}

  columnDefs = [
    {
      headerName: 'Id', field: 'id', sortable: true, filter: true,
      checkboxSelection: true, resizable: true,
    },
    {
      headerName: 'Name', field: 'name', sortable: true, filter: true,
      checkboxSelection: false, editable: true, resizable: true,
      comparator: this.customComparator,
    },
    {
      headerName: 'Description',  field: 'description', sortable: true, filter: true,
      checkboxSelection: false, editable: true, resizable: true,
    },
  ];

  customComparator(valueA, valueB) {
    return valueA.toLowerCase().localeCompare(valueB.toLowerCase());
  }

回答1:

This can be done by using a custom sorting function on the particular column that requires case-insensitive sorting.

For instance, for your columnDefs, if you require the name column to be sorted case insentitve, we pass the customComparator as the value for the comparator property. In your ngOnInit,

this.columnDefs = [
  {
    headerName: 'Name',
    field: 'name',
    sort: 'asc',  // optional, allows grid column to be sorted on init
    comparator: customComparator
  },
  // other columns
];

Then, we define the customComparator such that it carries out case-insentitive sorting. We do so by converting the values to lowercase on the custom comparator.

const customComparator = (valueA, valueB) => {
  return valueA.toLowerCase().localeCompare(valueB.toLowerCase());
};

EDIT: I have forked and recreated a demo from the original ag-grid demo to demonstrate the usage of the above comparator. Refer to the constructor() method for the relevant details.