LiveLoveApp logo

Row Sorting

Row Sorting

  • We can enable/disable the ability to sort a row using the sortable property in the ColDef.
  • The default sortable value is false.
  • Custom sorting can be performed using the comparator property, providing a sorting function similar to Array.prototype.sort().

Let's look an example:

@Component({
  selector: 'app-grid',
  standalone: true,
  imports: [AgGridModule],
  template: `
    <ag-grid-angular
      class="ag-theme-material"
      [columnDefs]="columnDefs"
      [rowData]="rowData"
    ></ag-grid-angular>
  `
})
export class GridComponent {
  columnDefs = [
    { headerName: 'Name', field: 'name', sortable: true },
    { headerName: 'Color', field: 'color' },
  ] as ColDef<RowData>[];

  rowData: RowData[] = products;
}

Sorting Order

By default the sorting order is set to:

  1. Ascending
  2. Descending
  3. None

We can specify the sortingOrder column definition property to override the default behavior.

Let's look at an example of specifying custom sorting order:

export class GridComponent {
  columnDefs = [
    {
      headerName: 'Name',
      field: 'name',
      sortable: true,
      sortingOrder: ['desc', 'asc', null]
    },
    { headerName: 'Color', field: 'color' },
  ] as ColDef<RowData>[];

  rowData: RowData[] = products;
}

Multi-column sorting

Users can sort multiple columns by holding the Shift-key and clicking on the column headers.

We can specify the multiSortKey table option to override the behavior.

@Component({
  selector: 'app-grid',
  standalone: true,
  imports: [AgGridModule],
  template: `
    <ag-grid-angular
      class="ag-theme-material"
      [columnDefs]="columnDefs"
      [rowData]="rowData"
      [multiSortKey]="ctrl"
    ></ag-grid-angular>
  `
})
export class GridComponent {}

This sets the sorting key to be the Command (macOS) or Ctrl (Windows) key.

Exercise

  1. Open the solution from the previous exercise on Stackblitz.
  2. Add the sortable property to a column definition.
  3. Override the default sorting order by specifying the sortingOrder property on the column definition.
  4. Override the default multi-column sorting key by specifying the multiSortKey input property on the <ag-grid-angular> component.

Solution

@Component({
  selector: 'app-grid',
  standalone: true,
  imports: [AgGridModule],
  template: `
    <ag-grid-angular
      class="ag-theme-material"
      [columnDefs]="columnDefs"
      [rowData]="rowData"
      [multiSortKey]="ctrl"
    ></ag-grid-angular>
  `
})
export class GridComponent {
  columnDefs = [
    {
      headerName: 'Name',
      field: 'name',
      sortable: true,
      sortingOrder: ['asc', 'desc']
    },
    { headerName: 'Color', field: 'color' },
  ] as ColDef<RowData>[];

  rowData: RowData[] = products;
}