# Using AG Grid Cell Rendering

Canonical page: https://www.adaptabletools.com/docs/dev-guide-aggrid-cell-rendering

- AG Grid Value Getters, Value Formatters and Cell Components all work in AdapTable
- Prefer AdapTable Formatting, Styling and Calculated Columns where they cover the same need

## AG Grid Rendering Objects

AG Grid provides very powerful functionality to enable custom cell and column content.

This is primarily achieved using 3 objects (depending on the complexity of the use case):

- [Value Formatters](https://www.ag-grid.com/javascript-data-grid/value-formatters/) — **format** the displayed value (essentially text formatting)
- [Cell Components](https://www.ag-grid.com/javascript-data-grid/cell-rendering/) — **display anything** in a cell
- [Value Getters](https://www.ag-grid.com/javascript-data-grid/value-getters/) — **retrieve** the cell value using custom logic

All of these work in AdapTable.

Where they cover the same need, we recommend using AdapTable objects instead:

- [Display Formats](https://www.adaptabletools.com/docs/handbook-column-formatting-display-format/index.md) in place of Value Formatters
- [Styling](https://www.adaptabletools.com/docs/handbook-column-formatting-adaptable-style/index.md) and [Styled Columns](https://www.adaptabletools.com/docs/handbook-styled-column-overview/index.md) in place of Cell Components
- [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) in place of Value Getters

Behind the scenes AdapTable converts its objects to AG Grid Value Formatters and Cell Components

This recommendation is made for a number of reasons, based on extensive user experience, including:

- AdapTable's objects can be changed at run-time via Wizards
- AdapTable's objects are fully saveable in State, and therefore shareable with colleagues
- AdapTable will ensure that they always work if AG Grid's api changes (i.e. they are future-proofed)

Keep an AG Grid Cell Component when the cell must show something AdapTable cannot author — for example an image, an interactive widget, or a third-party renderer

- [Export](https://www.adaptabletools.com/docs/handbook-exporting/index.md) can write the **display** value for a column that uses an AG Grid Value Formatter (or an AdapTable Display Format)
- It cannot do that for a column that uses an AG Grid Cell Component — only the raw value is available

**Example: AG Grid Cell Rendering & Formatting**

How AG Grid Cell Components, Value Formatters and Value Getters work with AdapTable

- This demo shows how AG Grid Cell Components, Value Formatters and Value Getters work with AdapTable
- The same fields are rendered with AG Grid and AdapTable options side by side:
  - `Made` appears twice, once with an [AG Grid Value Formatter](https://www.ag-grid.com/javascript-data-grid/value-formatters/) and once with an [AdapTable Date Display Format](https://www.adaptabletools.com/docs/handbook-column-formatting-display-format/index.md)
  - `Price` appears twice, once with an [AG Grid Value Formatter](https://www.ag-grid.com/javascript-data-grid/value-formatters/) and once with an [AdapTable Numeric Display Format](https://www.adaptabletools.com/docs/handbook-column-formatting-display-format/index.md)
  - `Rating` appears 3 times, once with an [AG Grid Value Formatter](https://www.ag-grid.com/javascript-data-grid/value-formatters/), once with an [AG Grid Cell Component](https://www.ag-grid.com/javascript-data-grid/cell-rendering/) and once with an [AdapTable Custom Display Format](https://www.adaptabletools.com/docs/handbook-column-formatting-display-format-custom/index.md)
  - `Composite` appears twice, once with an [AG Grid Value Getter](https://www.ag-grid.com/javascript-data-grid/value-getters/) and once using an [AdapTable Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md)
  - `Model` has an [AdapTable (Badge) Styled Column](https://www.adaptabletools.com/docs/handbook-styled-column-badge/index.md) configured in Initial Adaptable State

- Export `Current Layout` to Excel and compare the display values: Value Formatter and Display Format columns export formatted text; the Cell Component column does not

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  CustomDisplayFormatterContext,
} from '@adaptabletools/adaptable';
import {Car} from './rowData';

export const adaptableOptions: AdaptableOptions<Car> = {
  primaryKey: 'model',
  adaptableId: 'AG Grid Cell Rendering',
  formatColumnOptions: {
    customDisplayFormatters: [
      {
        id: 'ratingFormat',
        label: 'Rating Format',
        scope: {
          DataTypes: ['number'],
        },
        handler: (
          customDisplayFormatterContext: CustomDisplayFormatterContext
        ) => {
          const cellValue: number =
            customDisplayFormatterContext.cellValue as number;
          return '*'.repeat(cellValue);
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      PinnedToolbars: ['Export'],
    },
    Export: {
      CurrentReport: 'Current Layout',
      CurrentFormat: 'VisualExcel',
    },
    Theme: {CurrentTheme: 'dark'},
    StyledColumn: {
      StyledColumns: [
        {
          Name: 'model Badge',
          ColumnId: 'model',
          BadgeStyle: {
            Badges: [
              {
                PillStyle: {
                  BackColor: 'DarkGray',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
              },
            ],
          },
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-price_adaptable',
          Scope: {
            ColumnIds: ['price_adaptable'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 2,
              Prefix: '$',
            },
          },
        },
        {
          Name: 'formatColumn-made_adaptable',
          Scope: {
            ColumnIds: ['made_adaptable'],
          },
          DisplayFormat: {
            Formatter: 'DateFormatter',
            Options: {
              Pattern: 'dd/MM/yyyy',
            },
          },
        },
        {
          Name: 'formatColumn-rating_df',
          Scope: {
            ColumnIds: ['rating_df'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              CustomDisplayFormats: ['ratingFormat'],
            },
          },
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'composite_adaptable',
          FriendlyName: 'Composite (AdapTable)',
          CalculatedColumnSettings: {
            DataType: 'text',
          },
          Expression: '[make] + " - " + [model] ',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'make',
            'model',
            'made_aggrid',
            'made_adaptable',
            'price_aggrid',
            'price_adaptable',
            'rating_vf',
            'rating_cc',
            'rating_df',
            'composite_aggrid',
            'composite_adaptable',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';
import {rowData, Car} from './rowData';

export const gridOptions: GridOptions<Car> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';
import {Car} from './rowData';

export const columnDefs: ColDef<Car>[] = [
  {
    headerName: 'Make',
    field: 'make',
    filter: true,
    editable: false,
    enableRowGroup: true,
    enablePivot: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Model (SC)',
    field: 'model',
    filter: true,
    editable: false,
    cellDataType: 'text',
  },
  {
    headerName: 'Price (VF)',
    field: 'pricePerMile',
    colId: 'price_aggrid',
    filter: true,
    editable: false,
    cellDataType: 'number',
    valueFormatter: (params: any) => {
      return params.value
        ? params.value.toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
            style: 'currency',
            currency: 'USD',
          })
        : null;
    },
  },
  {
    headerName: 'Price (DF)',
    field: 'pricePerMile',
    colId: 'price_adaptable',
    filter: true,
    editable: false,
    cellDataType: 'number',
  },
  {
    headerName: 'Made (VF)',
    field: 'made',
    colId: 'made_aggrid',
    filter: true,
    editable: false,
    cellDataType: 'date',
    valueFormatter: (params: any) => {
      return params.value
        ? new Intl.DateTimeFormat('en-GB').format(params.value)
        : '';
    },
  },
  {
    headerName: 'Made (DF)',
    field: 'made',
    colId: 'made_adaptable',
    filter: true,
    editable: false,
    cellDataType: 'date',
  },
  {
    headerName: 'Available',
    field: 'available',
    filter: true,
    editable: true,
    cellDataType: 'boolean',
  },
  {
    headerName: 'Rating (VF)',
    field: 'rating',
    colId: 'rating_vf',
    enableValue: true,
    editable: true,
    sortable: true,
    valueFormatter: (params: any) => {
      let text = '';
      for (var i = 0; i < params.value; i++) {
        text += '*';
      }
      return text;
    },
    cellDataType: 'number',
    filter: true,
    enablePivot: true,
    resizable: true,
  },
  {
    headerName: 'Rating (CC)',
    field: 'rating',
    colId: 'rating_cc',
    enableValue: true,
    editable: true,
    sortable: true,
    cellRenderer: RatingRenderer,
    cellDataType: 'number',
    filter: true,
    enablePivot: true,
    resizable: true,
  },
  {
    headerName: 'Rating (DF)',
    field: 'rating',
    colId: 'rating_df',
    enableValue: true,
    editable: true,
    sortable: true,
    cellDataType: 'number',
    filter: true,
    enablePivot: true,
    resizable: true,
  },
  {
    headerName: 'Composite (AG)',
    editable: false,
    colId: 'composite_aggrid',
    filter: true,
    enableRowGroup: true,
    valueGetter: (params: any) => {
      return params.data && params.data.make && params.data.model
        ? params.data.make + ' - ' + params.data.model
        : undefined;
    },
    cellDataType: 'text',
  },
];

/*
The Cell Render for Rating.
We provide implementations for the init and getGui methods.
*/
function RatingRenderer() {}
RatingRenderer.prototype.init = function (params: any): any {
  this.eGui = document.createElement('span');
  var text = '';
  for (var i = 0; i < params.value; i++) {
    text += '*';
  }
  this.eGui.innerHTML = text;
};
RatingRenderer.prototype.getGui = function (): any {
  return this.eGui;
};
```

**`src/rowData.ts`**

```ts
export interface Car {
  make: string;
  model: string;
  made: Date;
  available: boolean;
  pricePerMile: number;
  rating: number;
}

export const rowData: Car[] = [
  {
    make: 'Toyota',
    model: 'Celica',
    made: new Date(2017, 11, 4),
    available: true,
    pricePerMile: 21.345676,
    rating: 1,
  },
  {
    make: 'Toyota',
    model: 'Yaris',
    made: new Date(2013, 1, 15),
    available: true,
    pricePerMile: 29.32432423,
    rating: 4,
  },
  {
    make: 'Toyota',
    model: 'Corolla',
    made: new Date(2017, 6, 9),
    available: false,
    pricePerMile: 32.9032523473287,
    rating: 5,
  },
  {
    make: 'Ford',
    model: 'Mondeo',
    made: new Date(2009, 10, 2),
    available: true,
    pricePerMile: 28.247893473289,
    rating: 4,
  },
  {
    make: 'Ford',
    model: 'Fiesta',
    made: new Date(2018, 8, 12),
    available: false,
    pricePerMile: 34.0001,
    rating: 5,
  },
  {
    make: 'Ford',
    model: 'Focus',
    made: new Date(2017, 3, 3),
    available: false,
    pricePerMile: 31.2432432423,
    rating: 3,
  },
  {
    make: 'Ford',
    model: 'Galaxy',
    made: new Date(2015, 4, 14),
    available: false,
    pricePerMile: 29.29432404,
    rating: 2,
  },
  {
    make: 'Porsche',
    model: 'Boxter',
    made: new Date(2016, 1, 28),
    available: true,
    pricePerMile: 32.29580292,
    rating: 4,
  },
  {
    make: 'Porsche',
    model: 'Mission',
    made: new Date(2008, 10, 7),
    available: false,
    pricePerMile: 35.7822957,
    rating: 5,
  },
  {
    make: 'Mitsubbishi',
    model: 'Outlander',
    made: new Date(2017, 11, 14),
    available: true,
    pricePerMile: 19.224309,
    rating: 4,
  },
];
```
