如何在 Angular 上为 ag-Grid 监听 sortChange(event)?

Tim*_*çek 1 javascript typescript ag-grid angular

我这里有非常基本的例子: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>
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用。它什么也不打印。你知道我如何用列名监听每一列的排序变化吗?

Ali*_*F50 5

它是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;
 }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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


小智 5

HTML:

    <ag-grid-angular>
     ...
     (sortChanged)="onSortChanged($event)">
    </ag-grid-angular>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

控制台日志示例:

{
    "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
}

Run Code Online (Sandbox Code Playgroud)