Ask Your Question

Revision history [back]

Row grouping and sorting can be implemented in Angular using the Ag-Grid library. The steps to implement this are:

  1. Install Ag-Grid library using npm:
npm install ag-grid-community ag-grid-angular
  1. Import Ag-Grid module in app.module.ts file:
import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  imports: [AgGridModule],
  ...
})
  1. Create an Ag-Grid component and define grid options:
<ag-grid-angular
    style="height: 500px;"
    class="ag-theme-balham"
    [rowData]="rowData"
    [columnDefs]="columnDefs"
    [enableSorting]="true"
    [enableFilter]="true"
    [groupUseEntireRow]="true"
    [groupDefaultExpanded]="1"
    [animateRows]="true"
    (gridReady)="onGridReady($event)">
</ag-grid-angular>

...

columnDefs = [
    { headerName: 'Country', field: 'country', rowGroup: true },
    { headerName: 'Year', field: 'year', sortable: true },
    { headerName: 'Gold', field: 'gold', sortable: true, filter: true },
    { headerName: 'Silver', field: 'silver', sortable: true, filter: true },
    { headerName: 'Bronze', field: 'bronze', sortable: true, filter: true },
    { headerName: 'Total', field: 'total', sortable: true, filter: true }
];

...

onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

    this.rowData = [
        { country: 'USA', year: '2016', gold: 46, silver: 37, bronze: 38, total: 121 },
        { country: 'China', year: '2016', gold: 26, silver: 18, bronze: 26, total: 70 },
        { country: 'UK', year: '2016', gold: 27, silver: 23, bronze: 17, total: 67 },
        { country: 'Russia', year: '2016', gold: 19, silver: 18, bronze: 19, total: 56 },
        { country: 'Germany', year: '2016', gold: 17, silver: 10, bronze: 15, total: 42 }
    ];
}
  1. Use the rowGroup option in columnDefs to group the rows based on a particular column. Use the sortable, filter and rowGroup options in the respective columns to enable sorting, filtering and row grouping.

  2. Use the onGridReady method to set the row data and get access to the grid API and column API.

  3. The grouping and sorting can be done by clicking on the column header. The groupDefaultExpanded option can be used to show the group by default. The groupUseEntireRow option can be used to expand or collapse the group by clicking on the plus/minus icon in the first column.