Search code examples
angularag-gridag-grid-angularag

How to know which Column is selected for Sort in Ag-Grid in Angular and is Acending or Decending


How to know which Column is selected for Sort in Ag-Grid in Angular and is Acending or Decending

Html

<ag-grid-angular 
    [enableSorting]="true"
    [rowData]="rowData" 
    [columnDefs]="columnDefs">
</ag-grid-angular>

ts

import {Component} from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    columnDefs = [
        {headerName: 'Make', field: 'make'},
        {headerName: 'Model', field: 'model'},
        {headerName: 'Price', field: 'price'}
    ];

    rowData = [
        {make: 'Toyota', model: 'Celica', price: 35000},
        {make: 'Ford', model: 'Mondeo', price: 32000},
        {make: 'Porsche', model: 'Boxter', price: 72000}
    ];
}

Suppose if i clicked on Make Columns once for making Accending i need to print in console sorted Filed Property Make and asc and again clicked on make Column will make accending filed to decending so it sould print on console Make and desc

also if i will take export by using this into csv file that sould export current selected Column sort as in csv sheet

Thanks In advance


Solution

  • You may use ag-grid's columnApi to fetch the columnState.

    In your component html, do the following :

    <ag-grid-angular
     [enableSorting]="true"
     [rowData]="rowData" 
     [columnDefs]="columnDefs"
     (gridReady)='onGridReady($event)'
     (sortChanged)='onSortChanged($event)'
    </ag-grid-angular>
    

    Next, in your component, do the following :

    public colApi : ColumnApi;
    
    onGridReady(event: GridReadyEvent): void
    {
      this.colApi = event.columnApi;
    }
    
    onSortChanged ()
    {
      let columnWithSort = this.colApi.getColumnState().find(col => col.sort !== null);
      console.log("Column that is sorted right now is " + columnWithSort.field);
      console.log("The sort order right now is " + columnWithSort.sort);  // prints "asc" or "desc"
    }
    
    

    You don't need to do any special handling for exporting the grid in a certain sort order. Ag-grid will export your current grid's column state as-is, to the exported format.