Row Sorting
Row Sorting
- We can enable/disable the ability to sort a row using the
sortable
property in theColDef
. - The default
sortable
value isfalse
. - Custom sorting can be performed using the
comparator
property, providing a sorting function similar toArray.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:
- Ascending
- Descending
- 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
- Open the solution from the previous exercise on Stackblitz.
- Add the
sortable
property to a column definition. - Override the default sorting order by specifying the
sortingOrder
property on the column definition. - 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;
}