# AG Grid

**AG Grid** is intended for highly complex, enterprise-level data grid use cases.

## Usage

It should be used only when requirements exceed what [ngx-datatable](<https://element.siemens.io/components/lists-tables-trees/ngx-datatable/>) can reasonably support, such as spreadsheet-like behavior, advanced cell logic, or highly customized interactions.

**AG Grid requires a paid license and introduces higher implementation and maintenance costs** Adoption should be justified by clear functional needs.

For AG Grid, we provide a theme to ensure visual alignment with Element. However, styling and behavior are partially constrained by AG Grid itself, so not all Element patterns and interactions can be fully enforced.

![AG Grid](<../images/ag-grid.png>)

## Code

> [!NOTE]
>
> **Required Packages**
>
> - [ag-grid-community](<https://www.npmjs.com/package/ag-grid-community>)

First, register the AG Grid modules in your `main.ts`:

```
import { ModuleRegistry, AllCommunityModule } from 'ag-grid-community';

ModuleRegistry.registerModules([AllCommunityModule]);
```

Then, add the Element AG Grid configuration provider in your `app.config.ts`:

```
import { provideSiAgGridConfig } from '@siemens/element-ng/ag-grid';

export const appConfig: ApplicationConfig = {
  providers: [provideSiAgGridConfig()]
};
```

You can also pass a density mode and custom grid options:

```
export const appConfig: ApplicationConfig = {
  providers: [
    provideSiAgGridConfig('compact', {
      rowHeight: 30,
      suppressMenuHide: true
    })
  ]
};
```

### Client side pagination

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { ColDef } from 'ag-grid-community';

import { TableData, TableDataService } from '../../mocks/table-data.mock';

@Component({
  selector: 'app-sample',
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [rowData]="rowData"
    [columnDefs]="colDefs"
    [defaultColDef]="defaultColDef"
    [pagination]="true"
    [paginationPageSize]="20"
    (gridReady)="onGridReady()"
  />`,
  host: {
    class: 'p-5'
  }
})
export class SampleComponent {
  private readonly tableDataService = inject(TableDataService);
  rowData: TableData[] = [];

  defaultColDef: ColDef<TableData> = {
    flex: 1
  };

  colDefs: ColDef<TableData>[] = [
    { field: 'id', headerName: 'ID' },
    { field: 'name' },
    { field: 'role' },
    { field: 'company' },
    { field: 'age' }
  ];

  onGridReady(): void {
    this.rowData = this.tableDataService.generateRows(500);
  }
}
```

### Infinite scroll

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject } from '@angular/core';
import { LOG_EVENT } from '@siemens/live-preview';
import { AgGridAngular } from 'ag-grid-angular';
import {
  CellValueChangedEvent,
  ColDef,
  GridOptions,
  GridReadyEvent,
  IDatasource,
  IGetRowsParams
} from 'ag-grid-community';

import { TableData, TableDataService } from '../../mocks/table-data.mock';

@Component({
  selector: 'app-sample',
  imports: [AgGridAngular],
  template: `
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [columnDefs]="colDefs"
      [defaultColDef]="defaultColDef"
      [gridOptions]="gridOptions"
      [rowSelection]="{
        mode: 'multiRow'
      }"
      (cellValueChanged)="onCellValueChanged($event)"
      (gridReady)="onGridReady($event)"
    />
  `,
  host: {
    class: 'p-5'
  }
})
export class SampleComponent {
  private logEvent = inject(LOG_EVENT);
  private readonly tableDataService = inject(TableDataService);
  private allData: TableData[] = [];

  gridOptions: GridOptions = {
    rowModelType: 'infinite',
    cacheBlockSize: 20,
    infiniteInitialRowCount: 10,
    cacheOverflowSize: 2,
    maxBlocksInCache: 2
  };

  colDefs: ColDef<TableData>[] = [
    {
      headerName: 'ID',
      maxWidth: 100,
      // it is important to have node.id here, so that when the id changes (which happens
      // when the row is loaded) then the cell is refreshed.
      valueGetter: 'node.id'
    },
    { field: 'name', minWidth: 150 },
    { field: 'role', minWidth: 150 },
    {
      field: 'age',
      valueFormatter: params => {
        if (params.value == null) return '';
        return params.value + ' years';
      }
    },
    { field: 'company', headerName: 'Company', minWidth: 150 }
  ];

  defaultColDef: ColDef<TableData> = {
    flex: 1,
    minWidth: 100,
    cellRenderer: (params: any) => {
      if (!params.node?.data) {
        // Return skeleton HTML for loading rows centered vertically
        return '<div style="display: flex; align-items: center; height: 100%;"><div class="ag-skeleton-effect"></div></div>';
      }
      return params.valueFormatted ?? params.value;
    }
  };

  onCellValueChanged(event: CellValueChangedEvent): void {
    this.logEvent('Cell Value Changed', event);
  }

  onGridReady(params: GridReadyEvent<TableData>): void {
    // Generate 500 rows of data
    this.allData = this.tableDataService.generateRows(500);

    const dataSource: IDatasource = {
      rowCount: undefined,
      getRows: (rowParams: IGetRowsParams) => {
        this.logEvent('asking for ' + rowParams.startRow + ' to ' + rowParams.endRow);
        // Simulate server delay
        setTimeout(() => {
          // Take a slice of the total rows
          const rowsThisPage = this.allData.slice(rowParams.startRow, rowParams.endRow);
          // If on or after the last page, work out the last row
          let lastRow = -1;
          if (this.allData.length <= rowParams.endRow) {
            lastRow = this.allData.length;
          }
          // Call the success callback
          rowParams.successCallback(rowsThisPage, lastRow);
        }, 5000);
      }
    };

    // Set datasource after render to avoid API call during render stage
    setTimeout(() => {
      params.api.setGridOption('datasource', dataSource);
    });
  }
}
```

### Empty state

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { ColDef } from 'ag-grid-community';

import { TableData } from '../../mocks/table-data.mock';

@Component({
  selector: 'app-sample',
  imports: [AgGridAngular],
  template: `
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [rowData]="rowData"
      [columnDefs]="colDefs"
      [defaultColDef]="defaultColDef"
      [noRowsOverlayComponentParams]="{
        icon: 'element-technical-operator',
        heading: 'No data to display',
        content: 'There are currently no rows to display in this table.'
      }"
    />
  `,
  host: {
    class: 'p-5'
  }
})
export class SampleComponent {
  rowData: TableData[] = []; // Empty array to show the overlay

  defaultColDef: ColDef<TableData> = {
    flex: 1
  };

  colDefs: ColDef<TableData>[] = [
    { field: 'id', headerName: 'ID' },
    { field: 'name' },
    { field: 'role' },
    { field: 'company' },
    { field: 'age' }
  ];
}
```

### Filter

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { ColDef } from 'ag-grid-community';

import { TableData, TableDataService } from '../../mocks/table-data.mock';

@Component({
  selector: 'app-sample',
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [columnDefs]="colDefs"
    [defaultColDef]="defaultColDef"
    [rowData]="rowData"
    [rowDragManaged]="true"
    (gridReady)="onGridReady()"
  /> `,
  host: {
    class: 'p-5'
  }
})
export class SampleComponent {
  private readonly tableDataService = inject(TableDataService);

  rowData: TableData[] = [];

  colDefs: ColDef<TableData>[] = [
    { field: 'id', headerName: 'ID', rowDrag: true },
    { field: 'name', filter: true, floatingFilter: true },
    { field: 'role' },
    {
      field: 'age',
      floatingFilter: true,
      filter: 'agNumberColumnFilter',
      valueFormatter: params => {
        if (params.value == null) return '';
        return params.value + ' years';
      }
    },
    { field: 'company', headerName: 'Company', filter: true },
    {
      field: 'dateOfJoining',
      headerName: 'Date of Joining',
      filter: 'agDateColumnFilter',
      floatingFilter: true,
      filterParams: {
        comparator: (filterLocalDateAtMidnight: Date, cellValue: Date) => {
          if (!cellValue) return -1;

          // Create date at midnight for comparison
          const cellDate = new Date(cellValue);
          cellDate.setHours(0, 0, 0, 0);

          const filterDate = new Date(filterLocalDateAtMidnight);
          filterDate.setHours(0, 0, 0, 0);

          if (cellDate < filterDate) {
            return -1;
          } else if (cellDate > filterDate) {
            return 1;
          }
          return 0;
        },
        buttons: ['clear', 'apply']
      }
    }
  ];

  defaultColDef: ColDef<TableData> = {
    flex: 1
  };

  onGridReady(): void {
    this.rowData = this.tableDataService.generateRows(100);
  }
}
```

### Row pinning

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { ColDef } from 'ag-grid-community';

import { TableData, TableDataService } from '../../mocks/table-data.mock';

@Component({
  selector: 'app-sample',
  imports: [AgGridAngular],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [rowData]="rowData"
    [columnDefs]="colDefs"
    [defaultColDef]="defaultColDef"
    [pinnedTopRowData]="pinnedTopRowData"
    (gridReady)="onGridReady()"
  />`,
  host: {
    class: 'p-5'
  }
})
export class SampleComponent {
  private readonly tableDataService = inject(TableDataService);
  rowData: TableData[] = [];
  pinnedTopRowData: TableData[] = [];

  defaultColDef: ColDef<TableData> = {
    flex: 1
  };

  colDefs: ColDef<TableData>[] = [
    { field: 'id', headerName: 'ID' },
    { field: 'name' },
    { field: 'role' },
    { field: 'company' },
    { field: 'age' }
  ];

  onGridReady(): void {
    const rows = this.tableDataService.generateRows(200);

    const [pinned, regular] = rows.reduce<[TableData[], TableData[]]>(
      (acc: [TableData[], TableData[]], row: TableData) => {
        (row.id < 3 ? acc[0] : acc[1]).push(row);
        return acc;
      },
      [[], []]
    );
    this.pinnedTopRowData = pinned;
    this.rowData = regular;
  }
}
```
