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

Viewed 6665

I have very basic example here: https://stackblitz.com/edit/angular-ag-grid-angular-cwvpic?file=app/my-grid-application/my-grid-application.component.ts

In this ag-grid I want to print which column clicked and ordered in what way.To do that basically I found method sortChange(event) on official docs.But I couldn't find a way to implement this method.Here what I tried.

 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>

Unfortunately this didn't work.It prints nothing.Do you know how I can listen sort changes on each column with column name?

1 Answers

It is sortChanged and not sortChange (has a d).

Try:

  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>

Edit: Your code is good, but you have to populate this.gridApi when the grid is ready like that (checkout (gridReady) and onGridReady). I get what you want to be logged into the console this way.

Related