Angular: Best way to set a default sort on a dynamic column in agGrid

Issue

I’m working on an agGrid, where we don’t explicitly define the columns. I can’t for the life of me figure out how to set a default sort on one of my columns. On init we do this:

public ngOnInit(): void {
    this.gridOptions.defaultColDef = this.selectable ? this.getDefaultColumnsDefinition() : null;
    this.showSpinner = true;
    this.getAllRefreshJobs();
}

It’s one of the columns in getDefaultColumnsDefinition() that I want to be sorted initially. I tried

public onGridReady(params): void {
    this.gridApi = params.api;
    const sortModel = [
        {colId: 'recordStartTime', sort: 'desc'}
    ];
    this.gridApi.setSortModel(sortModel);
    this.gridApi.sizeColumnsToFit();
}

but it doesn’t work. The grid looks the same. Can anyone help?

Solution

From what you have stated, you are calling the api before everything is initialized. I’m not 100% sure how you have this set up, but you should make these adjustments in the onGridReady function of your code. Within onGridReady you can do something similar to this:

HTML

<ag-grid-angular
    class="ag-theme-balham"
    [rowData]="data"
    [columnDefs]="columnDefs"
    (gridReady)="onGridReady($event)"></ag-grid-angular>

TypeScript

onGridReady(params): void {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    const sortModel = [
        {colId: 'recordStartTime', sort: 'desc'}
    ];
    this.gridApi.setSortModel(sortModel);
  }

This exposes the current gridApi and allows for you to make any post-initialization modifications.

Answered By – Jon

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published