Angular 2上的ag-grid +日期过滤器不起作用

时间:2017-12-19 11:07:34

标签: angular ag-grid

我在这里按照日期过滤的文档: https://www.ag-grid.com/javascript-grid-filter-date/#gsc.tab=0 但是,当我尝试过滤日期时,它只是不起作用。过滤后的结果与之前相同,而文本和数字等其他列则有效。核心问题应该在gridOptions内的Date对象中。我将Angular日期管道的日期显示格式设置为与ag-grid的过滤格式相同的格式,但实际日期数据是这样的: “2017-12-19T08:29:19Z”。我不知道它是否会影响过滤方法。

版本:Angular 4+,ag-grid 15.0.0,ag-grid-angular 15.0.0

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';    
import { GridOptions, GridApi } from "ag-grid";    
import { ApiService } from '../../services/api.service/api.service';
import * as Models from '../../models/models';    

@Component({
  selector: 'app-orders',
  templateUrl: './orders.component.html',
  styleUrls: ['./orders.component.scss']
})

export class OrdersComponent implements OnInit {

  gridOptions: GridOptions;

  gridApi: GridApi;
  gridColumnApi;

  rowSelection;

  orders: Models.Order[] = [];

  constructor(
    private apiService: ApiService,
    private modalService: NgbModal,
    private datePipe: DatePipe
  ) {
    this.gridOptions = <GridOptions>{};
    this.gridOptions.enableColResize = true;
    this.gridOptions.enableFilter = true;
    this.gridOptions.floatingFilter = true;
    this.gridOptions.enableSorting = true;

    this.gridOptions.columnDefs = [
      { headerName: 'Numero', field: 'id', valueFormatter: this.renderZeroPadding },
      { headerName: 'Date', field: 'order_date', 
        filter: 'agDateColumnFilter', cellRenderer: this.dateCellRenderer.bind(this), filterParams:{

          // provide comparator function
          comparator: function (filterLocalDateAtMidnight, cellValue) {

              var dateParts  = cellValue.split("/");
              var month = Number(dateParts[2]);
              var day = Number(dateParts[1]) - 1;
              var year = Number(dateParts[0]);
              var cellDate = new Date(month, day, year);

              // Now that both parameters are Date objects, we can compare
              if (cellDate < filterLocalDateAtMidnight) {
                  return -1;
              } else if (cellDate > filterLocalDateAtMidnight) {
                  return 1;
              } else {
                  return 0;
              }
          }
      } },
    ];
    // allow single row selection only
    this.rowSelection = "single";
  }

  ngOnInit() {
    // get orders and set the values to grid
    this.apiService.getOrders()
      .subscribe((orders: Models.Order[]) => {
        this.orders = orders;
        this.gridOptions.api.setRowData(orders);
      })
  }

  onReady(params) {
    this.gridApi = params.api;
    const self = this;
    setTimeout(function () { self.gridApi.sizeColumnsToFit(); }, 1000);
  }

  // modify the date to wanted format
  dateCellRenderer(params: any) {
    return this.datePipe.transform(params.value, 'MM/dd/yyyy');
  }

  // add zeros to beginning to make id 8 characters 
  renderZeroPadding(params: any) {
    let pad = "00000000";
    return (pad + params.value).slice(-pad.length)
  }    
}

3 个答案:

答案 0 :(得分:1)

尝试使用下面的比较器:

{
      "SubscriptionId": "xxxxxxxx",
      "PreviousWatermark": "xxxxxxxx",
      "MoreEvents": "false",
      "CreatedEvent": {
        "Watermark": "xxxxx",
        "TimeStamp": "2018-08-13T13:18:12Z",
        "ItemId": "",
        "ParentFolderId": ""
      },
      "ModifiedEvent": [
        {
          "Watermark": "xxxxxxx",
          "TimeStamp": "2018-08-13T13:18:13Z",
          "ItemId": "",
          "ParentFolderId": ""
        },
        {
          "Watermark": "xxxxxxx",
          "TimeStamp": "2018-08-13T13:18:13Z",
          "FolderId": "",
          "ParentFolderId": ""
        }
      ]
    }

Plunker

答案 1 :(得分:0)

添加过滤器:“ agDateColumnFilter”

{
    headerName: Date,
    filter:'agDateColumnFilter',
    valueFormatter: function(params){
       return moment(param.value).format('MM/DD/YYY');
    }
}

答案 2 :(得分:0)

基于 soaib 的回答和参考https://blog.ag-grid.com/valueformatters-part-2/

当您的日期格式类似于“2017-12-19T08:29:19Z”时,您必须转换为日期对象,例如“2021 年 6 月 24 日星期四 00:00:00 GMT+0700(印度尼西亚西部时间)”在过滤器参数->比较器中。

这是如何使用 moment js 执行此操作的代码片段

filterParams={{
  buttons: ["reset"],
  comparator: (filterLocalDateAtMidnight, cellValue) => {
    const cellDate = moment(cellValue).startOf("day").toDate();

    if (filterLocalDateAtMidnight.getTime() == cellDate.getTime()) {
      return 0;
    }

    if (cellDate < filterLocalDateAtMidnight) {
      return -1;
    }

    if (cellDate > filterLocalDateAtMidnight) {
      return 1;
    }
  },
}}

如您所见,为什么我将时间设置为 0?那是因为如果你的日期格式有一个像“05:20:27”这样的时间,然后你将它与为 0 的 filterLocalDateAtMidnight.getTime() 进行比较,它不会比较任何东西。所以你必须把小时改成0。