Ag 网格 - 如何对列进行排序以将所有空值显示为最后?

Dom*_*nik 3 javascript ag-grid

我想创建一个自定义比较器来对列进行升序/降序排序,但在这两种情况下,我想将所有空(空)值保留在列表末尾

我使用 valueGetter 返回正确的字符串值/null。

Gur*_*hra 8

我认为你可以通过两种方式实现这一目标

第一:对要使用自定义排序的列使用比较器

   columnDefs: [
        { 
            field: 'columnName', 
              comparator: (a, b, nodeA, nodeB, isInverted) => {
            if (a === b) {
                return 0;
              }
              // for null
             else if (a === 'null') {
                 return isInverted ?-1: 1;
             }
             else if (b === 'null') {
                 return isInverted ? 1: -1;
             }
             else { 
                return a.localeCompare(b);
             }

         }
}]
        
Run Code Online (Sandbox Code Playgroud)
  1. a,b:要比较的单元格中的值。通常仅对这些值进行排序。
  2. nodeA、nodeB:要排序的行的行节点。如果需要更多信息(例如其他列的数据)进行比较,则可以使用这些信息。
  3. isInverted: true 表示升序, false 表示降序。

第二:使用 postSort 机制,一旦所有内容排序完毕就会调用它

     <GridOptions> {
                  postSort:  this.postSort 
                  }// add this to grid options
          
 private postSort = function(rowNodes) {
    // null value data will be sorted at the end

    function checkNull(node) {
        return node.data.Id ===  null ; // if id is column is the one we are chceking
    }

    function move(toIndex, fromIndex) {
        rowNodes.splice(toIndex, 0, rowNodes.splice(fromIndex, 1)[0]);
    }

    var nextInsertPos = rowNodes.length; //last index

    for (var i = 0; i < rowNodes.length; i++) {
        if (rowNodes[i].data && checkNull(rowNodes[i])) {
            move(nextInsertPos, i)
            nextInsertPos++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)