【问题标题】:ag-Grid - how to force custom sorting after data is added or modifiedag-Grid - 添加或修改数据后如何强制自定义排序
【发布时间】:2020-09-18 16:10:46
【问题描述】:

我正在尝试在我的Ionic 4/Angular 8 应用程序中对 ag-Grid 中的列使用自定义排序。

我有一个示例应用程序 hereStackblitz 我无法让它在 Stackblitz 上运行,但它可以在本地运行,

无论如何,有几点需要注意的是,我希望网格在虚拟模式下运行(例如,可能有 1000 行数据),并且我还设置了 this.gridOptions.immutableData = true; 来处理来自 ng/rx 的数据。

我也使用组件作为单元格模板,但我认为我们可以在这里忽略它(使用现有示例)

我希望对行进行排序,因此同时调用我的 dateComparator 函数

  • 当我第一次加载数据时
  • 如果我有任何数据添加或更新

为了模拟来自服务器的新数据,我有一个调用 add 方法的添加按钮。

我在专栏中添加了comparator...

        public ngAfterViewInit(): void {                
            const self = this;
            this.gridOptions.immutableData = true;
            this.gridOptions.animateRows = true
            this.gridOptions.api.setColumnDefs([
            {
                    headerName: 'myheader',
                    comparator: self.dateComparator,
                    sortable: true,
                    field: 'equipment',
                    cellStyle: { padding: 0 },        
                    cellRendererFramework: TemplateRendererComponent,              
                    cellRendererParams: {
                        ngTemplate: this.itemCard
                    },        
                },
            ]);

            this.setData();
            }

    private dateComparator(valueA, valueB, nodeA, nodeB, isInverted): number {
       console.log('sorting');
       return 1;
     }

但是,当我加载网格或调用上面的 add 方法时,我的 dateComparator 没有被调用。仅当我单击列标题时才会调用它。

我尝试调用this.gridOptions.api.redrawRows(),但这不会导致它排序。我看不到任何其他明显的 sort 函数可以调用。

我的问题是,如何在不点击列标题的情况下自动应用这种排序(即当我加载或更新我的数据时)?

【问题讨论】:

    标签: angular ag-grid ag-grid-angular


    【解决方案1】:

    要对列进行默认排序,你必须在colDef中指定排序属性 -

    sort: 'desc', // asc or desc
    

    您也可以在使用排序 api 初始化网格后执行此操作 -

    var sort = [
      {
        colId: 'country',
        sort: 'asc',
      },
      {
        colId: 'sport',
        sort: 'asc',
      },
    ];
    this.gridApi.setSortModel(sort); // provide sort model here
    

    现在,当您的数据更新并且您需要让网格知道以根据您的自定义比较器维护排序时,您需要调用 - onSortChanged()

    根据文档-

    onSortChanged()
    使网格表现得好像排序已更改。如果您更新一些值并希望让网格变为 根据新值重新排序。

    排序模型应用示例here

    【讨论】:

    • 非常感谢!似乎只是添加了排序:'asc' 现在让我的 comparator 方法现在在第一次添加数据时和添加新数据时都被调用。在我的简单测试中,我什至不需要调用 onSortChanged(),但如果我开始更复杂的更新后我看不到排序自己工作,我会记住这一点。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 2021-11-18
    • 2016-06-15
    • 1970-01-01
    • 2016-08-04
    • 2021-06-10
    • 2019-12-15
    • 2016-06-22
    相关资源
    最近更新 更多