---
title: "Row Sorting"
framework: angular
version: "36.1.0"
---

# Row Sorting

This page describes how to sort row data in the grid and how you can customise that sorting to match your requirements.

## Sorting

Sorting is enabled by default for all columns. You can sort a column by clicking on the column header. To enable / disable sorting per column use the `sortable` column definition attribute.

```ts
<ag-grid-angular
    [columnDefs]="columnDefs"
    /* other grid options ... */ />

this.columnDefs = [
    { field: 'name' },
    { field: 'age' },
    // disable sorting by address
    { field: 'address', sortable: false },
];
```

To disable sorting for all columns, set sorting in the [default column definition](https://www.ag-grid.com/angular-data-grid/column-definitions/).

```ts
<ag-grid-angular
    [defaultColDef]="defaultColDef"
    [columnDefs]="columnDefs"
    /* other grid options ... */ />

// disable sorting on all columns
this.defaultColDef = {
    sortable: false
};
this.columnDefs = [
    // Override default to enable sorting by name
    { field: 'name', sortable: true },
    { field: 'age' },
    { field: 'address' },
];
```

## Custom Sorting

Custom sorting is provided at a column level by configuring a comparator on the column definition.

```ts
<ag-grid-angular
    [columnDefs]="columnDefs"
    /* other grid options ... */ />

this.columnDefs = [
    {
        field: 'age',
        // simple number comparator
        comparator: (valueA, valueB, nodeA, nodeB, isDescending) => valueA - valueB
    },
    {
        field: 'name',
        // simple string comparator
        comparator: (valueA, valueB, nodeA, nodeB, isDescending) => {
            if (valueA == valueB) return 0;
            return (valueA > valueB) ? 1 : -1;
        }
    }
];
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `comparator` | `SortComparatorFn \| Partial<Record<SortType, SortComparatorFn>>` |  |  | Override the default sorting order by providing a custom sort comparator, or a map of comparators for different `SortType`s. - `valueA`, `valueB` are the values to compare. - `nodeA`, `nodeB` are the corresponding RowNodes. Useful if additional details are required by the sort. - `isDescending` - `true` if sort direction is `desc`. Not to be used for inverting the return value as the grid already applies `asc` or `desc` ordering. Returns: - `0` valueA is the same as valueB - `> 0` Sort valueA after valueB - `< 0` Sort valueA before valueB |

Example below shows the following:

- The **Athlete** column is sorted descending on load.
- When the **Year** column is not sorted, it shows a custom icon (up/down arrow).
- The **Date** column has strings as the row data, but has a custom comparator so that when you sort this column it sorts as dates, not as strings.

#### Custom Sorting

```ts
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import "./style.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
  /> `,
})
export class AppComponent {
  columnDefs: ColDef[] = [
    { field: "athlete", sort: "desc" },
    { field: "age", width: 90 },
    { field: "country" },
    { field: "year", width: 120, unSortIcon: true },
    { field: "date", comparator: dateComparator },
    { field: "sport" },
  ];
  defaultColDef: ColDef = {
    width: 170,
  };
  rowData!: IOlympicData[];

  constructor(private http: HttpClient) {}

  onGridReady(params: GridReadyEvent<IOlympicData>) {
    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => (this.rowData = data.slice(0, 10)));
  }
}

function dateComparator(date1: string, date2: string) {
  const date1Number = monthToComparableNumber(date1);
  const date2Number = monthToComparableNumber(date2);
  if (date1Number === null && date2Number === null) {
    return 0;
  }
  if (date1Number === null) {
    return -1;
  }
  if (date2Number === null) {
    return 1;
  }
  return date1Number - date2Number;
}
// eg 29/08/2004 gets converted to 20040829
function monthToComparableNumber(date: string) {
  if (date === undefined || date === null || date.length !== 10) {
    return null;
  }
  const yearNumber = Number.parseInt(date.substring(6, 10));
  const monthNumber = Number.parseInt(date.substring(3, 5));
  const dayNumber = Number.parseInt(date.substring(0, 2));
  return yearNumber * 10000 + monthNumber * 100 + dayNumber;
}
```

[Live example: Custom Sorting](https://www.ag-grid.com/examples/row-sorting/custom-sorting/angular)

> **Note**
>
> If you are using a custom column header component see [Custom Components](https://www.ag-grid.com/angular-data-grid/column-headers-components/#custom-component) for how to implement sorting.

## Multi Column Sorting

It is possible to sort by multiple columns. The default action for multiple column sorting is for the user to hold down `⇧ Shift` while clicking the column header. To change the default action to use the `^ Ctrl` key instead set the property `multiSortKey='ctrl'`.

The example below demonstrates the following:

- The grid sorts by **Country** then **Athlete** by default.
- The property `multiSortKey='ctrl'` is set so multiple column sorting is achieved by holding down `^ Ctrl` and selecting multiple columns.

#### Multi Column Sort

```ts
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  ColumnState,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ColumnApiModule, ClientSideRowModelModule]);
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [multiSortKey]="multiSortKey"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
  /> `,
})
export class AppComponent {
  columnDefs: ColDef[] = [
    { field: "athlete" },
    { field: "age", width: 100 },
    { field: "country" },
    { field: "year", width: 100 },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ];
  defaultColDef: ColDef = {
    width: 170,
  };
  multiSortKey: "ctrl" = "ctrl";
  rowData!: IOlympicData[];

  constructor(private http: HttpClient) {}

  onGridReady(params: GridReadyEvent<IOlympicData>) {
    const defaultSortModel: ColumnState[] = [
      { colId: "country", sort: "asc", sortIndex: 0 },
      { colId: "athlete", sort: "asc", sortIndex: 1 },
    ];
    params.api.applyColumnState({ state: defaultSortModel });

    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Multi Column Sort](https://www.ag-grid.com/examples/row-sorting/multi-column/angular)

> **Note**
>
> You can suppress the multi sorting behaviour by enabling the `suppressMultiSort` option, or force the behaviour without key press by enabling the `alwaysMultiSort` option.

## Sorting Animation

By default rows will animate after sorting. If you wish to suppress this animation set the grid property `animateRows=false`.

## Sorting Order

By default, the sorting order is as follows:

**ascending -> descending -> none**.

In other words, when you click a column that is not sorted, it will sort ascending. The next click will make it sort descending. Another click will remove the sort.

It is possible to override this behaviour by providing your own `sortingOrder` on the `colDef`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sortingOrder` | `(SortDirection \| SortDef)[]` |  |  | An array defining the order in which sorting occurs (if sorting is enabled). Defaults: - `['asc', 'desc', null]` if no sort type is specified, - `[{ type: 'absolute', direction: 'asc', }, { type: 'absolute', direction: 'desc' }, null]` if 'sort' or 'initialSort' have type 'absolute' |

The example below shows different combinations of sorting orders as follows:

- **Column Athlete:** ascending -> descending
- **Column Age:** descending -> ascending
- **Column Country:** descending -> no sort
- **Column Year:** ascending only
- **Default Columns:** descending -> ascending -> no sort

#### Sorting Order and Animation

```ts
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
  /> `,
})
export class AppComponent {
  columnDefs: ColDef[] = [
    { field: "athlete", sortingOrder: ["asc", "desc"] },
    { field: "age", width: 90, sortingOrder: ["desc", "asc"] },
    { field: "country", sortingOrder: ["desc", null] },
    { field: "year", width: 90, sortingOrder: ["asc"] },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ];
  defaultColDef: ColDef = {
    width: 170,
    sortingOrder: ["desc", "asc", null],
  };
  rowData!: IOlympicData[];

  constructor(private http: HttpClient) {}

  onGridReady(params: GridReadyEvent<IOlympicData>) {
    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Sorting Order and Animation](https://www.ag-grid.com/examples/row-sorting/sorting-order-and-animation/angular)

## Absolute Sorting

Absolute Sorting enables sorting numeric values based on their magnitude, ignoring their sign. This can be used to rank values by their size ignoring if a value is positive or negative.

In the following example, the column `rankingChange` uses absolute sorting:

```ts
<ag-grid-angular
    [columnDefs]="columnDefs"
    /* other grid options ... */ />

this.columnDefs = [
    // ... other columns
    {
        field: 'rankingChange',
        sort: { direction: 'asc', type: 'absolute' },
        sortingOrder: [
            { direction: 'asc', type: 'absolute' },
            { direction: 'desc', type: 'absolute' },
            null,
        ],
    },
];
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `SortDirection \| SortDef` |  |  | Set the default sort. |
| `sortingOrder` | `(SortDirection \| SortDef)[]` |  |  | An array defining the order in which sorting occurs (if sorting is enabled). Defaults: - `['asc', 'desc', null]` if no sort type is specified, - `[{ type: 'absolute', direction: 'asc', }, { type: 'absolute', direction: 'desc' }, null]` if 'sort' or 'initialSort' have type 'absolute' |

#### Absolute Value Sorting

```ts
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);
import { any } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
  /> `,
})
export class AppComponent {
  columnDefs: ColDef[] = [
    { field: "athlete", minWidth: 150 },
    { field: "year", maxWidth: 90 },
    {
      field: "rankingChange",
      sort: { direction: "asc", type: "absolute" },
      sortingOrder: [
        { direction: "asc", type: "absolute" },
        { direction: "desc", type: "absolute" },
        null,
      ],
    },
  ];
  defaultColDef: ColDef = {
    flex: 1,
    minWidth: 100,
  };
  rowData!: any[];

  constructor(private http: HttpClient) {}

  onGridReady(params: GridReadyEvent) {
    this.http
      .get<
        any[]
      >("https://www.ag-grid.com/example-assets/small-olympic-winners.json")
      .subscribe(
        (data) =>
          (this.rowData = data.map((item) => {
            return {
              ...item,
              rankingChange: Math.round(window.agRandom() * 10) - 5,
            };
          })),
      );
  }
}
```

[Live example: Absolute Value Sorting](https://www.ag-grid.com/examples/row-sorting/absolute-sorting/angular)

## Sorting API

> **Note**
>
> The sort state can be saved and restored as part of [Grid State](https://www.ag-grid.com/angular-data-grid/grid-state/).

What sorting is applied is controlled via [Column State](https://www.ag-grid.com/angular-data-grid/column-state/). The below examples uses the Column State API to control column sorting.

#### Sorting API

```ts
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import "./styles.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  NumberFilterModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  TextFilterModule,
  NumberFilterModule,
  ClientSideRowModelModule,
  ColumnApiModule,
]);
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<div class="example-wrapper">
    <div style="margin-bottom: 1rem">
      <div>
        <button (click)="sortByAthleteAsc()">Athlete Ascending</button>
        <button (click)="sortByAthleteDesc()">Athlete Descending</button>
        <button (click)="sortByCountryThenSport()">Country, then Sport</button>
        <button (click)="sortBySportThenCountry()">Sport, then Country</button>
      </div>
      <div style="margin-top: 0.25rem">
        <button (click)="clearSort()">Clear Sort</button>
        <button (click)="saveSort()">Save Sort</button>
        <button (click)="restoreFromSave()">Restore from Save</button>
      </div>
    </div>
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [columnDefs]="columnDefs"
      [rowData]="rowData"
      (gridReady)="onGridReady($event)"
    />
  </div> `,
})
export class AppComponent {
  private gridApi!: GridApi<IOlympicData>;

  columnDefs: ColDef[] = [
    { field: "athlete" },
    { field: "age", width: 90 },
    { field: "country" },
    { field: "sport" },
    { field: "year", width: 90 },
    { field: "date" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ];
  rowData!: IOlympicData[];

  constructor(private http: HttpClient) {}

  sortByAthleteAsc() {
    this.gridApi.applyColumnState({
      state: [{ colId: "athlete", sort: "asc" }],
      defaultState: { sort: null },
    });
  }

  sortByAthleteDesc() {
    this.gridApi.applyColumnState({
      state: [{ colId: "athlete", sort: "desc" }],
      defaultState: { sort: null },
    });
  }

  sortByCountryThenSport() {
    this.gridApi.applyColumnState({
      state: [
        { colId: "country", sort: "asc", sortIndex: 0 },
        { colId: "sport", sort: "asc", sortIndex: 1 },
      ],
      defaultState: { sort: null },
    });
  }

  sortBySportThenCountry() {
    this.gridApi.applyColumnState({
      state: [
        { colId: "country", sort: "asc", sortIndex: 1 },
        { colId: "sport", sort: "asc", sortIndex: 0 },
      ],
      defaultState: { sort: null },
    });
  }

  clearSort() {
    this.gridApi.applyColumnState({
      defaultState: { sort: null },
    });
  }

  saveSort() {
    const colState = this.gridApi.getColumnState();
    const sortState = colState
      .filter(function (s) {
        return s.sort != null;
      })
      .map(function (s) {
        return { colId: s.colId, sort: s.sort, sortIndex: s.sortIndex };
      });
    savedSort = sortState;
    console.log("saved sort", sortState);
  }

  restoreFromSave() {
    this.gridApi.applyColumnState({
      state: savedSort,
      defaultState: { sort: null },
    });
  }

  onGridReady(params: GridReadyEvent<IOlympicData>) {
    this.gridApi = params.api;

    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => (this.rowData = data));
  }
}

let savedSort: any;
```

[Live example: Sorting API](https://www.ag-grid.com/examples/row-sorting/sorting-api/angular)

## Locale-specific Sort

By default, sorting is not locale-specific and strings are compared using their Unicode code point order. There is no language awareness and no locale rules are applied. If you need to make your sort locale-specific you can configure this by setting the grid option `accentedSort = true`.

> **Note**
>
> Locale-specific sort is slower than default sort which may be noticeable when sorting a large number of rows.

Toggle the buttons in the following example to see the difference between default sorting and locale-aware sorting. Note that with locale-aware sorting, the order is `a à b c` instead of the default Unicode order of `a b c à`.

#### Locale Aware Sort

```ts
import { Component } from "@angular/core";
import { AgGridAngular } from "ag-grid-angular";
import "./styles.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<div class="test-container">
    <div class="test-header">
      <button (click)="applyLocale()">Locale-specific Sort</button>
      <button (click)="applyDefault()">Default Sort</button>
    </div>
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      class="test-grid"
      [columnDefs]="columnDefs"
      [accentedSort]="true"
      [rowData]="rowData"
      (gridReady)="onGridReady($event)"
    />
  </div> `,
})
export class AppComponent {
  private gridApi!: GridApi;

  columnDefs: ColDef[] = [
    { headerName: "Locale-specific Sort", field: "letter", sort: "asc" },
  ];
  rowData: any[] | null = [..."bàac"].map((x) => ({ letter: x }));

  applyLocale() {
    this.gridApi.updateGridOptions({
      accentedSort: true,
      columnDefs: [
        { field: "letter", sort: "asc", headerName: "Locale-specific Sort" },
      ],
    });
  }

  applyDefault() {
    this.gridApi.updateGridOptions({
      accentedSort: false,
      columnDefs: [
        { field: "letter", sort: "asc", headerName: "Default Sort" },
      ],
    });
  }

  onGridReady(params: GridReadyEvent) {
    this.gridApi = params.api;
  }
}
```

[Live example: Locale Aware Sort](https://www.ag-grid.com/examples/row-sorting/locale-aware-sort/angular)

## Post-Sort

It is also possible to perform some post-sorting if you require additional control over the sorted rows.

This is provided via the `postSortRows` grid callback function as shown below:

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `postSortRows` | `PostSortRows` |  |  | Callback to perform additional sorting after the grid has sorted the rows. When configured, `deltaSort` is ignored. |

```ts
<ag-grid-angular
    [postSortRows]="postSortRows"
    /* other grid options ... */ />

this.postSortRows = params => {
    let rowNodes = params.nodes;
    // here we put Ireland rows on top while preserving the sort order
    let nextInsertPos = 0;
    for (let i = 0; i < rowNodes.length; i++) {
        const country = rowNodes[i].data.country;
        if (country === 'Ireland') {
            rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
            nextInsertPos++;
        }
    }
};
```

The following example uses this configuration to perform a post-sort on the rows. The custom function puts rows with Ireland at the top always.

#### Post Sort

```ts
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  PostSortRows,
  PostSortRowsParams,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [postSortRows]="postSortRows"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
  /> `,
})
export class AppComponent {
  columnDefs: ColDef[] = [
    { field: "athlete" },
    { field: "age", width: 100 },
    { field: "country", sort: "asc" },
    { field: "year" },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ];
  defaultColDef: ColDef = {
    width: 170,
  };
  postSortRows: PostSortRows = (params: PostSortRowsParams<IOlympicData>) => {
    const rowNodes = params.nodes;
    // here we put Ireland rows on top while preserving the sort order
    let nextInsertPos = 0;
    for (let i = 0; i < rowNodes.length; i++) {
      const country = rowNodes[i].data ? rowNodes[i].data!.country : undefined;
      if (country === "Ireland") {
        rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
        nextInsertPos++;
      }
    }
  };
  rowData!: IOlympicData[];

  constructor(private http: HttpClient) {}

  onGridReady(params: GridReadyEvent<IOlympicData>) {
    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => {
        this.rowData = data;
      });
  }
}
```

[Live example: Post Sort](https://www.ag-grid.com/examples/row-sorting/post-sort/angular)
