---
title: "Cell Components"
framework: angular
version: "36.1.0"
---

# Cell Components

Custom HTML / DOM inside Cells is achieved using Cell Components. Create Custom Cell Components to have any HTML markup in a cell. The grid comes with some Provided Cell Components for common grid tasks.

[Angular Cell Renderers](https://www.youtube.com/watch?v=xsafnM77NVs)

The example below shows adding images, hyperlinks, and buttons to a cell using Custom Cell Components. The custom button logs to the developer console when clicked.

#### Simple Cell Renderer

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

ModuleRegistry.registerModules([CellStyleModule, ClientSideRowModelModule]);
import { CompanyLogoRenderer } from "./companyLogoRenderer.component";
import { CompanyRenderer } from "./companyRenderer.component";
import { CustomButtonComponent } from "./customButtonComponent.component";
import { MissionResultRenderer } from "./missionResultRenderer.component";
import { PriceRenderer } from "./priceRenderer.component";

interface IRow {
  company: string;
  website: string;
  revenue: number;
  hardware: boolean;
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [
    AgGridAngular,
    CompanyLogoRenderer,
    CompanyRenderer,
    CustomButtonComponent,
    MissionResultRenderer,
    PriceRenderer,
  ],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [defaultColDef]="defaultColDef"
    [columnDefs]="columnDefs"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
  /> `,
})
export class AppComponent {
  defaultColDef: ColDef = {
    flex: 10,
  };
  columnDefs: ColDef[] = [
    {
      field: "company",
      flex: 6,
    },
    {
      field: "website",
      cellRenderer: CompanyRenderer,
    },
    {
      headerName: "Logo",
      field: "company",
      cellRenderer: CompanyLogoRenderer,
      cellClass: "logoCell",
      minWidth: 100,
    },
    {
      field: "revenue",
      cellRenderer: PriceRenderer,
      flex: 8,
    },
    {
      field: "hardware",
      cellRenderer: MissionResultRenderer,
      flex: 8,
    },
    {
      colId: "actions",
      headerName: "Actions",
      cellRenderer: CustomButtonComponent,
      minWidth: 160,
    },
  ];
  rowData!: IRow[];

  constructor(private http: HttpClient) {}

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

[Live example: Simple Cell Renderer](https://www.ag-grid.com/examples/component-cell-renderer/cell-renderer-summary/angular)

## Provided Components

The grid comes with some built in Cell Components that cover some common cell rendering requirements.

- [Group Cell Component](https://www.ag-grid.com/angular-data-grid/grouping-single-group-column/#cell-component): For showing group details with expand and collapse functionality when using any of [Row Grouping](https://www.ag-grid.com/angular-data-grid/grouping/), [Master Detail](https://www.ag-grid.com/angular-data-grid/master-detail/) or [Tree Data](https://www.ag-grid.com/angular-data-grid/tree-data/).
- [Animate Change Cell Renderers](https://www.ag-grid.com/angular-data-grid/change-cell-renderers/#animated-cell-renderers): For animating changes when data is updated.
- [Checkbox Cell Renderer](https://www.ag-grid.com/angular-data-grid/cell-data-types/#boolean): For displaying boolean values with a checkbox when `cellDataType` of Boolean is used.

## Custom Components

To render custom content in a grid cell, first define the custom cell component and then configure the column definition to use the component via `cellRenderer` or `cellRendererSelector`, passing custom parameters via `cellRendererParams` as required.

### Creating Custom Components

A cell renderer is either:

- A function returning an HTML string or a DOM object
- A class implementing the [`ICellRendererAngularComp`](#api-reference) interface

Use the function variant of a Cell Component if you have no refresh requirements.

```ts
interface ICellRendererAngularComp {
    // Mandatory - Params for rendering
    agInit(params: ICellRendererParams): void;

    // Mandatory - Return true if you have managed the cell refresh yourself in this method, otherwise return false.
    // If you return false, the grid will remove the component from the DOM and create a new component in its place
    // with the new values.
    refresh(params: ICellRendererParams): boolean;
}
```

When providing a class-based component, it is initialised with `props` containing, amongst other things, the value to be rendered. The full definition can be found below in the [API Reference](#api-reference).

```ts
class CustomButtonComponent implements ICellRendererAngularComp {
  // ...
  agInit(props: ICellRendererParams): void {
    this.cellValue = props.value;
  }
  // ...
```

When using a function-based component, it receives the same `props` as its argument as would have been provided to the `agInit` method above. In the example below we're outputting a string value that depends on the cell value:

```js
@Component({
    selector: 'my-app',
    template: `
        <ag-grid-angular
                [columnDefs]="columnDefs"
                ...other properties />`
})
export class AppComponent {
    columnDefs = [
        {
            headerName: "Value",
            field: "value",
            cellRenderer: params => params.value > 1000 ? "LARGE VALUE" : "SMALL VALUE"
        }
    ];
    //...
}
```

It is also possible to write a JavaScript-based Cell Renderer Component - refer to the [documentation here](https://www.ag-grid.com/javascript-data-grid/component-cell-renderer/#creating-custom-components) for more information

### Providing Custom Components

The Cell Component for a Column is set via `colDef.cellRenderer` and can be any of the following types:

1. `String`: The name of a registered Cell Component, see [Registering Custom Components](https://www.ag-grid.com/angular-data-grid/components/#registering-custom-components)
2. `Class`: Direct reference to a Cell Component.
3. `Function`: A function that returns either an HTML string or DOM element for display.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cellRenderer` | `any` |  |  | Provide your own cell Renderer component for this column's cells. |

The code snippet below demonstrates each of these method types.

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

this.columnDefs = [
    // 1 - String - The name of a Cell Component registered with the grid.
    {
        field: 'age',
        cellRenderer: 'agGroupCellRenderer',
    },
    // 2 - Class - Provide your own Cell Component directly without registering.
    {
        field: 'sport',
        cellRenderer: MyCustomCellRendererClass,
    },
    // 3 - Function - A function that returns an HTML string or DOM element for display
    {
        field: 'year',
        cellRenderer: params => {
            // put the value in bold
            return 'Value is <b>' + params.value + '</b>';
        }
    }
];
```

### Providing Custom Components Dynamically

The `colDef.cellRendererSelector` function allows setting different Cell Components for different Rows within a Column.

The `params` passed to `cellRendererSelector` are the same as those passed to the [Cell Renderer Component](https://www.ag-grid.com/angular-data-grid/component-cell-renderer/). Typically the selector will use this to check the row's contents and choose a renderer accordingly.

The result is an object with `component` and `params` to use instead of `cellRenderer` and `cellRendererParams`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cellRendererSelector` | `CellRendererSelectorFunc` |  |  | Callback to select which cell renderer to be used for a given row within the same column. |

This following shows the selector choosing between Mood and Gender Cell Renderers based on the row data.

```js
cellRendererSelector: params => {

    const type = params.data.type;

    if (type === 'gender') {
        return {
            component: GenderCellRenderer,
            params: {values: ['Male', 'Female']}
        };
    }

    if (type === 'mood') {
        return {
            component: MoodCellRenderer
        };
    }

    return undefined;
}
```

Another use case for the Selector function is to only render a custom cell component in leaf nodes when [Row Grouping](https://www.ag-grid.com/angular-data-grid/grouping/). This is done by checking `params.node.group` and returning `undefined` for the group nodes.

```js
cellRendererSelector: params => {
    return params.node.group ? undefined : { component: CellRenderer };
},
```

The example below demonstrates the use of `cellRendererSelector` to dynamically select a Cell Component based on the row data.

- The column 'Value' holds data of different types as shown in the column 'Type' (numbers/genders/moods).
- `colDef.cellRendererSelector` is a function that selects the renderer based on the row data.
- The column 'Rendered Value' show the data rendered applying the component and params specified by `colDef.cellRendererSelector`

#### Dynamic Rendering Component

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

ModuleRegistry.registerModules([ClientSideRowModelModule]);
import { GenderRenderer } from "./gender-renderer.component";
import { MoodRenderer } from "./mood-renderer.component";

interface IRow {
  value: number | string;
  type: "age" | "gender" | "mood";
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular, GenderRenderer, MoodRenderer],
  template: `<ag-grid-angular
    style="width: 100%; height: 100%;"
    [rowData]="rowData"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
  /> `,
})
export class AppComponent {
  rowData: IRow[] | null = [
    { value: 14, type: "age" },
    { value: "Female", type: "gender" },
    { value: "Happy", type: "mood" },
    { value: 21, type: "age" },
    { value: "Male", type: "gender" },
    { value: "Sad", type: "mood" },
  ];
  columnDefs: ColDef[] = [
    { field: "value" },
    {
      headerName: "Rendered Value",
      field: "value",
      cellRendererSelector: (params: ICellRendererParams<IRow>) => {
        const moodDetails = {
          component: MoodRenderer,
        };
        const genderDetails = {
          component: GenderRenderer,
          params: { values: ["Male", "Female"] },
        };
        if (params.data) {
          if (params.data.type === "gender") return genderDetails;
          else if (params.data.type === "mood") return moodDetails;
        }
        return undefined;
      },
    },
    { field: "type" },
  ];
  defaultColDef: ColDef = {
    flex: 1,
    cellDataType: false,
  };
}
```

[Live example: Dynamic Rendering Component](https://www.ag-grid.com/examples/component-cell-renderer/dynamic-rendering-component/angular)

### Custom Props

The `props` passed to the Cell Component can be complemented with custom props. This allows configuring reusable Cell Components - e.g. a component could have buttons that are optionally displayed via additional props.

Complement props to a cell renderer using the Column Definition attribute `cellRendererParams`. When provided, these props will be merged with the grid provided props.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cellRendererParams` | `any` |  |  | Params to be passed to the `cellRenderer` component. |

```js
// define Cell Component to be reused
@Component({
    selector: 'colour-cell',
    template: `<span [style.color]="params.color">{{params.value}}</span>`
})
class ColourCellComp implements ICellRendererAngularComp {
    params!: ICellRendererParams;

    agInit(params: ICellRendererParams) {
        this.params = params;
    }

    refresh(params: ICellRendererParams) {
        this.params = params;
        // As we have updated the params we return true to let AG Grid know we have handled the refresh.
        // So AG Grid will not recreate the cell renderer from scratch.
        return true;
    }
}

@Component({
    selector: 'my-app',
    template: `
        <ag-grid-angular
                [columnDefs]="columnDefs"
                ...other properties />`
})
export class AppComponent {
    columnDefs = [
        {
            headerName: "Colour 1",
            field: "value",
            cellRenderer: ColourCellComp,
            cellRendererParams: {
                color: 'guinnessBlack'
            }
        },
        {
            headerName: "Colour 2",
            field: "value",
            cellRenderer: ColourCellComp,
            cellRendererParams: {
                color: 'irishGreen'
            }
        }
    ];

    //...
}

```

This example shows rendering an image with and without custom props and using custom props to pass a callback to a button. The `Refresh Data` button triggers the cell components to refresh by randomising the success data. The `Launch` button logs a message to the developer console.

#### Custom Props

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

ModuleRegistry.registerModules([
  RowApiModule,
  ClientSideRowModelModule,
  ClientSideRowModelApiModule,
]);
import { CustomButtonComponent } from "./customButtonComponent.component";
import { MissionResultRenderer } from "./missionResultRenderer.component";

interface IRow {
  company: string;
  location: string;
  price: number;
  successful: boolean;
}

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular, CustomButtonComponent, MissionResultRenderer],
  template: `<div class="example-wrapper">
    <div style="margin-bottom: 5px">
      <button (click)="refreshData()">Refresh Data</button>
    </div>
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [columnDefs]="columnDefs"
      [defaultColDef]="defaultColDef"
      [rowData]="rowData"
      (gridReady)="onGridReady($event)"
    />
  </div> `,
})
export class AppComponent {
  private gridApi!: GridApi<IRow>;

  columnDefs: ColDef[] = [
    {
      field: "company",
    },
    {
      field: "successful",
      headerName: "Success",
      cellRenderer: MissionResultRenderer,
    },
    {
      field: "successful",
      headerName: "Success (Custom Props)",
      cellRenderer: MissionResultRenderer,
      cellRendererParams: {
        src: successIconSrc,
      },
    },
    {
      colId: "actions",
      headerName: "Actions",
      cellRenderer: CustomButtonComponent,
      cellRendererParams: (params: any) => ({
        onClick: onClick,
        params,
      }),
      sortable: false,
    },
  ];
  defaultColDef: ColDef = {
    flex: 1,
  };
  rowData!: IRow[];

  constructor(private http: HttpClient) {}

  refreshData() {
    this.gridApi.forEachNode((rowNode) => {
      rowNode.setDataValue("successful", window.agRandom() > 0.5);
    });
    this.gridApi.refreshClientSideRowModel("sort");
  }

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

    this.http
      .get<
        IRow[]
      >("https://www.ag-grid.com/example-assets/small-space-mission-data.json")
      .subscribe((data) => {
        this.rowData = data;
      });
  }
}

// Override the icons via cellRendererParams
function successIconSrc(params: boolean) {
  if (params === true) {
    return "https://www.ag-grid.com/example-assets/svg-icons/tick.svg";
  } else {
    return "https://www.ag-grid.com/example-assets/svg-icons/cross.svg";
  }
}
const onClick = () => console.log("Mission Launched");
```

[Live example: Custom Props](https://www.ag-grid.com/examples/component-cell-renderer/custom-props/angular)

### Dynamic Tooltips

When working with Custom Cell Renderers it is possible to register custom tooltips that are displayed dynamically by calling the `setTooltip` method on the params passed to the component.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `setTooltip` | `Function` |  |  | Sets a tooltip to the main element of this component. `value` The value to be displayed by the tooltip `shouldDisplayTooltip` A function returning a boolean that allows the tooltip to be displayed conditionally. This option does not work when `enableBrowserTooltips={true}`. |

The example below demonstrates a dynamic tooltip being displayed on Cell Components. The following can be noted:

- The Athlete column uses the `shouldDisplayTooltip` callback to only display Tooltips when the text is not fully displayed.

#### Dynamic Tooltips

```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,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  TextEditorModule,
  TextFilterModule,
  TooltipModule,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  TextEditorModule,
  TextFilterModule,
  ClientSideRowModelModule,
  TooltipModule,
]);
import { AthleteCellRenderer } from "./athlete-cell-renderer.component";
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular, AthleteCellRenderer],
  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", width: 120, cellRenderer: AthleteCellRenderer },
    { field: "country", width: 150 },
  ];
  defaultColDef: ColDef = {
    editable: true,
    minWidth: 100,
    filter: true,
  };
  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: Dynamic Tooltips](https://www.ag-grid.com/examples/component-cell-renderer/dynamic-tooltips/angular)

### Defer Slow Cell Components

If a Custom Cell Component is slow to render, the grid may appear unresponsive due to the custom component blocking the main thread. This can be avoided by deferring the rending of slow components as follows:

```js
{
    cellRenderer: 'SlowCellRenderer',
    cellRendererParams: {
        deferRender: true
    }
}
```

Deferred components will be rendered after other cells and only after the grid has stopped scrolling. In the meantime, the loading cell renderer will be displayed. If [Row Grouping](https://www.ag-grid.com/angular-data-grid/grouping/) is active only custom cells in leaf nodes will be deferred.

The example below demonstrates the use of `deferRender` to defer the rendering of an artificially slow cell component. The following can be noted when scrolling:

- The column 'Slow Renderer' is deferred and shows the default skeleton cell loader.
- The column 'Slow Renderer Custom' is deferred but uses a custom loading cell defined via `colDef.loadingCellRenderer`.
- The column 'Fast Renderer' is a custom component but not deferred so renders immediately along with the other plain cells.
- The `cellRendererSelector` only returns the Slow Cell Renderer for leaf nodes as an optimisation.

#### Slow Cell Renderer

```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,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ICellRendererParams,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { RowGroupingModule } from "ag-grid-enterprise";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule, RowGroupingModule]);
import { CustomLoadingCellRenderer } from "./custom-loading-cell-renderer.component";
import { FastRenderer } from "./fastRenderer.component";
import { SlowRenderer } from "./slowRenderer.component";
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [
    AgGridAngular,
    CustomLoadingCellRenderer,
    FastRenderer,
    SlowRenderer,
  ],
  template: `<div class="example-wrapper">
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [rowBuffer]="rowBuffer"
      [groupDefaultExpanded]="groupDefaultExpanded"
      [columnDefs]="columnDefs"
      [defaultColDef]="defaultColDef"
      [rowData]="rowData"
      (gridReady)="onGridReady($event)"
    />
  </div> `,
})
export class AppComponent {
  rowBuffer = 5;
  groupDefaultExpanded = 1;
  columnDefs: ColDef[] = [
    {
      field: "athlete",
      rowGroup: true,
      hide: true,
    },
    {
      field: "country",
      headerName: "Slow Renderer",
      cellRendererSelector: (params: ICellRendererParams) => {
        // Optimisation to only use the slow renderer for leaf nodes and not for groups
        return params.node.group ? undefined : { component: SlowRenderer };
      },
      cellRendererParams: {
        deferRender: true,
      },
    },
    {
      field: "bronze",
      headerName: "Slow Renderer Custom",
      cellRendererSelector: (params: ICellRendererParams) => {
        // Optimisation to only use the slow renderer for leaf nodes and not for groups
        return params.node.group ? undefined : { component: SlowRenderer };
      },
      cellRendererParams: {
        deferRender: true,
      },
      loadingCellRenderer: CustomLoadingCellRenderer,
    },
    {
      field: "gold",
      headerName: "Fast Renderer",
      cellRenderer: FastRenderer,
    },
    {
      field: "sport",
    },
  ];
  defaultColDef: ColDef = {
    flex: 1,
    autoHeaderHeight: true,
    wrapHeaderText: true,
  };
  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: Slow Cell Renderer](https://www.ag-grid.com/examples/component-cell-renderer/slow-cell-renderer/angular)

### Accessing Instances

After the grid has created an instance of a Cell Component for a cell it is possible to access that instance. This is useful if you want to call a method that you provide on the Cell Component that has nothing to do with the operation of the grid. Accessing Cell Components is done using the grid API `getCellRendererInstances(params)`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `getCellRendererInstances` | `Function` |  |  | Returns the list of active cell renderer instances. Module: [`RenderApiModule`](https://www.ag-grid.com/angular-data-grid/modules/). |

An example of getting the Cell Component for exactly one cell is as follows:

```js
// example - get cell renderer for first row and column 'gold'
const firstRowNode = api.getDisplayedRowAtIndex(0);
const params = { columns: ['gold'], rowNodes: [firstRowNode] };
const instances = api.getCellRendererInstances(params);

if (instances.length > 0) {
    // got it, user must be scrolled so that it exists
    const instance = instances[0];
}
```

Note that this method will only return instances of the Cell Component that exists. Due to Row and Column Virtualisation, Cell Components will only exist for Cells that are within the viewport of the Vertical and Horizontal scrolls.

The example below demonstrates custom methods on Cell Components called by the application. The following can be noted:

- The medal columns are all using the user defined `MedalCellRenderer`. The Cell Component has an arbitrary method `medalUserFunction()` which prints some data to the developer console.
- The **Gold** button executes a method on all instances of the Cell Component in the gold column and prints the data to the developer console.
- The **First Row Gold** button executes a method on the gold cell of the first row only and prints data to the developer console. Note that the `getCellRendererInstances()` method will return nothing if the grid is scrolled far past the first row showing row virtualisation in action.
- The **All Cells** button executes a method on all instances of all Cell Components and prints data to the developer console.

#### Get Cell Renderer

```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,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  NumberEditorModule,
  NumberFilterModule,
  RenderApiModule,
  RowApiModule,
  TextEditorModule,
  TextFilterModule,
  ValueGetterParams,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  RenderApiModule,
  NumberEditorModule,
  TextEditorModule,
  TextFilterModule,
  NumberFilterModule,
  RowApiModule,
  ClientSideRowModelModule,
]);
import { MedalCellRenderer } from "./medal-cell-renderer.component";
import { IOlympicData } from "./interfaces";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular, MedalCellRenderer],
  template: `<div class="example-wrapper">
    <div style="margin-bottom: 5px">
      <button (click)="onCallGold()">Gold</button>
      <button (click)="onFirstRowGold()">First Row Gold</button>
      <button (click)="onCallAllCells()">All Cells</button>
    </div>

    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [columnDefs]="columnDefs"
      [defaultColDef]="defaultColDef"
      [rowData]="rowData"
      (gridReady)="onGridReady($event)"
    />
  </div> `,
})
export class AppComponent {
  private gridApi!: GridApi<IOlympicData>;

  columnDefs: ColDef[] = [
    { field: "athlete", width: 150 },
    { field: "country", width: 150 },
    { field: "year", width: 100 },
    { field: "gold", width: 100, cellRenderer: MedalCellRenderer },
    { field: "silver", width: 100, cellRenderer: MedalCellRenderer },
    { field: "bronze", width: 100, cellRenderer: MedalCellRenderer },
    {
      field: "total",
      editable: false,
      valueGetter: (params: ValueGetterParams) =>
        params.data.gold + params.data.silver + params.data.bronze,
      width: 100,
    },
  ];
  defaultColDef: ColDef = {
    editable: true,
    flex: 1,
    minWidth: 100,
    filter: true,
  };
  rowData!: IOlympicData[];

  constructor(private http: HttpClient) {}

  onCallGold() {
    console.log("=========> calling all gold");
    // pass in list of columns, here it's gold only
    const params = { columns: ["gold"] };
    const instances = this.gridApi.getCellRendererInstances(params) as any[];
    instances.forEach((instance) => {
      instance.medalUserFunction();
    });
  }

  onFirstRowGold() {
    console.log("=========> calling gold row one");
    // pass in one column and one row to identify one cell
    const firstRowNode = this.gridApi.getDisplayedRowAtIndex(0)!;
    const params = { columns: ["gold"], rowNodes: [firstRowNode] };
    const instances = this.gridApi.getCellRendererInstances(params) as any[];
    instances.forEach((instance) => {
      instance.medalUserFunction();
    });
  }

  onCallAllCells() {
    console.log("=========> calling everything");
    // no params, goes through all rows and columns where cell renderer exists
    const instances = this.gridApi.getCellRendererInstances() as any[];
    instances.forEach((instance) => {
      instance.medalUserFunction();
    });
  }

  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;
      });
  }
}
```

[Live example: Get Cell Renderer](https://www.ag-grid.com/examples/component-cell-renderer/get-cell-renderer/angular)

### Keyboard Navigation

When using custom Cell Components, the custom Cell Component is responsible for implementing support for keyboard navigation among its focusable elements. This is why by default, focusing a grid cell with a custom Cell Component will focus the entire cell instead of any of the elements inside the custom cell renderer.

In order to handle focus in your custom cell component, implement [Custom Cell Component Keyboard Navigation](https://www.ag-grid.com/angular-data-grid/keyboard-navigation/#custom-cell-component).

### Handling Mouse Events

By default when a cell is clicked on, the grid will perform actions including:

- Focusing the cell.
- Updating the cell selection, if [Cell Selection](https://www.ag-grid.com/angular-data-grid/cell-selection/) is enabled.
- Selecting the row, if [Row Selection](https://www.ag-grid.com/angular-data-grid/row-selection/) is enabled.
- Starting editing, if [Editing](https://www.ag-grid.com/angular-data-grid/cell-editing/) is enabled.

This behaviour may not be desirable for custom cell components, e.g. if they contain interactive elements. In this situation, the grid can be prevented from handling the mouse event (`'click'`, `'dblclick'`, `'mousedown'` or `'touchstart'`), by passing the `suppressMouseEventHandling` callback to `cellRendererParams`.

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

this.columnDefs = [
    {
        colId: 'customButton',
        cellRenderer: CustomButtonComponent,
        cellRendererParams: {
            suppressMouseEventHandling: (params) => true,
        },
    },
];
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `suppressMouseEventHandling` | `Function` |  |  | Return `true` to prevent the grid from handling the following mouse events: `'click'`, `'dblclick'`, `'mousedown'`, `'touchstart'`. This will prevent actions performed via the mouse, such as focusing a cell, selecting a row, starting a cell selection, or starting an edit. This will not prevent the grid from firing events for these mouse events (e.g. `onCellClicked`), but the events will have the `isEventHandlingSuppressed` property set to match the return value. |

Note that whilst the callback will prevent the grid from performing actions, it will still continue to fire events (e.g. `onCellClicked`). These events will have the `isEventHandlingSuppressed` property set to `true` if the callback returns `true`.

The following example demonstrates using `suppressMouseEventHandling` with cell selection, row selection, and editing. Mouse events are suppressed for the Button column.

#### Handling Mouse Events

```ts
import { Component } from "@angular/core";
import { AgGridAngular } from "ag-grid-angular";
import "./styles.css";
import {
  CellClickedEvent,
  CellDoubleClickedEvent,
  CellMouseDownEvent,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  EventCellRendererParams,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  NumberEditorModule,
  RowClickedEvent,
  RowDoubleClickedEvent,
  RowSelectionModule,
  SuppressMouseEventHandlingParams,
  TextEditorModule,
  enableDevValidations,
} from "ag-grid-community";
import { CellSelectionModule } from "ag-grid-enterprise";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  ClientSideRowModelModule,
  CellSelectionModule,
  RowSelectionModule,
  TextEditorModule,
  NumberEditorModule,
]);
import { CustomButtonComponent } from "./customButtonComponent.component";

@Component({
  selector: "my-app",
  standalone: true,
  imports: [AgGridAngular, CustomButtonComponent],
  template: `<div class="example-wrapper">
    <div style="margin-bottom: 5px">
      <button id="enableCellSelection" (click)="toggleCellSelection()">
        Enable Cell Selection
      </button>
      <button id="rowSelection" (click)="toggleRowSelection()">
        Enable Row Selection
      </button>
    </div>
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      [rowData]="rowData"
      [defaultColDef]="defaultColDef"
      [columnDefs]="columnDefs"
      (cellClicked)="onCellClicked($event)"
      (cellMouseDown)="onCellMouseDown($event)"
      (cellDoubleClicked)="onCellDoubleClicked($event)"
      (rowClicked)="onRowClicked($event)"
      (rowDoubleClicked)="onRowDoubleClicked($event)"
      (gridReady)="onGridReady($event)"
    />
  </div> `,
})
export class AppComponent {
  private gridApi!: GridApi;

  rowData: any[] | null = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  defaultColDef: ColDef = {
    editable: true,
  };
  columnDefs: ColDef[] = [
    {
      field: "id",
    },
    {
      colId: "customButton",
      headerName: "Button",
      cellRenderer: CustomButtonComponent,
      cellRendererParams: {
        suppressMouseEventHandling: (
          params: SuppressMouseEventHandlingParams,
        ) => {
          console.log("suppressMouseEventHandling", params);
          return true;
        },
      } as EventCellRendererParams,
    },
  ];

  onCellClicked(e: CellClickedEvent) {
    console.log(
      e.type,
      "isEventHandlingSuppressed",
      e.isEventHandlingSuppressed,
    );
  }

  onCellMouseDown(e: CellMouseDownEvent) {
    console.log(
      e.type,
      "isEventHandlingSuppressed",
      e.isEventHandlingSuppressed,
    );
  }

  onCellDoubleClicked(e: CellDoubleClickedEvent) {
    console.log(
      e.type,
      "isEventHandlingSuppressed",
      e.isEventHandlingSuppressed,
    );
  }

  onRowClicked(e: RowClickedEvent) {
    console.log(
      e.type,
      "isEventHandlingSuppressed",
      e.isEventHandlingSuppressed,
    );
  }

  onRowDoubleClicked(e: RowDoubleClickedEvent) {
    console.log(
      e.type,
      "isEventHandlingSuppressed",
      e.isEventHandlingSuppressed,
    );
  }

  toggleCellSelection() {
    const enableCellSelection = !this.gridApi.getGridOption("cellSelection");
    this.gridApi.setGridOption("cellSelection", enableCellSelection);
    document.querySelector("#enableCellSelection")!.textContent =
      enableCellSelection ? "Disable Cell Selection" : "Enable Cell Selection";
  }

  toggleRowSelection() {
    const oldRowSelection = this.gridApi.getGridOption("rowSelection");
    this.gridApi.setGridOption(
      "rowSelection",
      oldRowSelection
        ? undefined
        : {
            mode: "multiRow",
            enableClickSelection: true,
          },
    );
    document.querySelector("#rowSelection")!.textContent = !oldRowSelection
      ? "Disable Row Selection"
      : "Enable Row Selection";
  }

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

[Live example: Handling Mouse Events](https://www.ag-grid.com/examples/component-cell-renderer/handling-mouse-events/angular)

It is also possible to stop propagation on mouse events from within a custom cell component, but this must be done for each of the mouse events described above.

### API Reference

Properties available on the `ICellRendererComp&lt;TData = any&gt;` interface.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `getGui` | `Function` |  |  | Return the DOM element of your component, this is what the grid puts into the DOM |
| `destroy` | `Function` |  |  | Gets called once by grid when the component is being removed; if your component needs to do any cleanup, do it here |
| `init` | `Function` |  |  | The init(params) method is called on the component once. |
| `refresh` | `Function` |  |  | Get the cell to refresh. Return true if successful. Return false if not (or you don't have refresh logic), then the grid will refresh the cell for you. |

Properties available on the `ICellRendererParams&lt;TData = any, TValue = any, TContext = any&gt;` interface.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | [`TValue \| null \| undefined`](https://www.ag-grid.com/angular-data-grid/typescript-generics/#cell-value-tvalue) |  |  | Value to be rendered. |
| `valueFormatted` | `string \| null \| undefined` |  |  | Formatted value to be rendered. |
| `fullWidth` | `boolean` |  |  | True if this is a full width row. |
| `pinned` | `'left' \| 'right' \| null` |  |  | Pinned state of the cell. |
| `data` | [`TData \| undefined`](https://www.ag-grid.com/angular-data-grid/typescript-generics/#row-data-tdata) |  |  | The row's data. Data property can be `undefined` when row grouping or loading infinite row models. |
| `node` | [`IRowNode`](https://www.ag-grid.com/angular-data-grid/row-object/) |  |  | The row node. |
| `colDef` | [`ColDef`](https://www.ag-grid.com/angular-data-grid/column-properties/) |  |  | The cell's column definition. |
| `column` | [`Column`](https://www.ag-grid.com/angular-data-grid/column-object/) |  |  | The cell's column. |
| `eGridCell` | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |  |  | The grid's cell, a DOM div element. |
| `eParentOfValue` | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) |  |  | The parent DOM item for the cell renderer, same as eGridCell unless using checkbox selection. |
| `getValue` | `Function` |  |  | Convenience function to get most recent up to data value. |
| `setValue` | `Function` |  |  | Convenience function to set the value. |
| `formatValue` | `Function` |  |  | Convenience function to format a value using the column's formatter. |
| `refreshCell` | `Function` |  |  | Convenience function to refresh the cell. |
| `registerRowDragger` | `Function` |  |  | registerRowDragger: `rowDraggerElement` The HTMLElement to be used as Row Dragger `dragStartPixels` The amount of pixels required to start the drag (Default: 4) `value` The value to be displayed while dragging. Note: Only relevant with Full Width Rows. `suppressVisibilityChange` Set to `true` to prevent the Grid from hiding the Row Dragger when it is disabled. |
| `setTooltip` | `Function` |  |  | Sets a tooltip to the main element of this component. `value` The value to be displayed by the tooltip `shouldDisplayTooltip` A function returning a boolean that allows the tooltip to be displayed conditionally. This option does not work when `enableBrowserTooltips={true}`. |
| `api` | [`GridApi`](https://www.ag-grid.com/angular-data-grid/grid-api/) |  |  | The grid api. |
| `context` | [`TContext`](https://www.ag-grid.com/angular-data-grid/typescript-generics/#context-tcontext) |  |  | Application context as set on `gridOptions.context`. |
