繁体   English   中英

如何在 Angular 上收听 ag-Grid 的 sortChange(event)?

[英]How to listen sortChange(event) on Angular for ag-Grid?

我这里有非常基本的例子: https://stackblitz.com/edit/angular-ag-grid-angular-cwvpic?file=app/my-grid-application/my-grid-application.component.ts

在这个ag-grid中,我想打印哪一列被点击并以什么方式排序。基本上我在官方文档上找到了方法sortChange(event) 。但是我找不到实现这个方法的方法。这是我尝试过的.

 sortChange(event){
      console.log(event);
    }

<div style="width: 200px;">
    <ag-grid-angular
     (sortChange)="sortChange($event)" 
     #agGrid style="width: 100%; height: 200px;" 
    class="ag-theme-fresh" [gridOptions]="gridOptions">
    </ag-grid-angular>
</div>

不幸的是,这没有用。它什么都不打印。你知道我如何用列名收听每一列的排序变化吗?

它是sortChanged而不是sortChange (有广告)。

尝试:

  printSortStateToConsole() {
    const sortState = this.gridApi.getSortModel();
    if (sortState.length == 0) {
      console.log("No sort active");
    } else {
      console.log("State of sorting is:");
      for (var i = 0; i < sortState.length; i++) {
        const item = sortState[i];
        console.log(i + " = {colId: " + item.colId + ", sort: " + item.sort + "}");
      }
    }
  }

onGridReady(params: any) {
      this.gridApi = params.api;
 }
<div style="width: 200px;">
    <ag-grid-angular
       #agGrid style="width: 100%; height: 200px;" 
       class="ag-theme-fresh"
       (sortChanged)="printSortStateToConsole($event)"
       (gridReady)="onGridReady($event)"
       [gridOptions]="gridOptions">
    </ag-grid-angular>
</div>

编辑:您的代码很好,但是您必须在网格准备就绪时填充this.gridApi (结帐(gridReady)onGridReady )。 我得到了你想要以这种方式登录到控制台的内容。

HTML:

    <ag-grid-angular>
     ...
     (sortChanged)="onSortChanged($event)">
    </ag-grid-angular>

TS:

onSortChanged(event) {
    const sortedColumn = event.columnApi.getColumnState().find(col => Boolean(col.sort));
    console.log(sortedColumn, '>> col sort state <<');

  // here you can do the logic for the sorted column and direction

控制台日志示例:

{
    "colId": "created_at",
    "width": 233,
    "hide": false,
    "pinned": null,
    "sort": "asc",
    "sortIndex": 0,
    "aggFunc": null,
    "rowGroup": false,
    "rowGroupIndex": null,
    "pivot": false,
    "pivotIndex": null,
    "flex": null
}

如果您使用的是 AgGridReact,那么您可以使用以下方式来收听过滤器更改

<Grid onSortChanged={onSortChanged}/>

const onSortChanged = (params) => {
    params.columnApi.getColumnState().find(s => s.sort != null)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM