Cell Renderer Function
The cellRenderer
function
- After the value for a cell is determined, and we have optionally formatted the value, we can use a cell renderer to have full control of how a cell is rendered in AG Grid.
- It's important to note that we should only use a cell renderer when necessary.
- By default, the
textContent
of the cell HTML element is set to the (optionally formatted) value. - When we are using a cell renderer we are often adding additional elements, event listeners, etc. to the DOM, all of which must be rendered for each cell in the grid.
The cellRenderer
for a column definition accepts the following values:
undefined
will render the cell's (optionally formatted) value as thetextContent
of the cell.- A string that references a registered cell renderer.
- A class of a cell renderer component.
- A function that returns either an
HTMLElement
or string that is injected as the cell'sinnerHtml
.
Before we dive into using the cellRenderer
function, let's look at the CellRendererParams<TData, TValue>
interface.
interface ValueFormatterParams<TData = any, TValue = any> {
api: GridApi<TData>;
colDef: ColDef<TData>;
column: Column;
columnApi: ColumnApi;
context: any;
data: TData | undefined;
node: RowNode<TData> | null;
value: TValue;
}
Let's look at an example of a cellRenderer
function:
export class GridComponent {
columnDefs = [
{
headerName: 'price',
cellRenderer: (params) => {
if (params.value === undefined) {
return null;
}
return this.currencyPipe.transform(params.value);
},
},
] as ColDef<RowData>[];
}
In the example, rather than using a valueFormatter
for the Price
field we are using a cellRenderer
.
- We injected the
CurrentPipe
into the Angular component. - The
cellRenderer
function accepts theparams
object. - First, we check if the
value
is undefined. - Then, we invoke and return the value from the
transform()
method.
Exercise
The goal of this exercise is to learn how to use the cellRenderer
function.
- Open the exercise on Stackblitz.
- Add a
cellRenderer
to theDate of Order
column. - First, check if the
value
is notundefined
in theparams
object. - Return a string of the HTML that includes a Material Icon next to the formatted date string.
Hint:
- Since we are not using an Angular component, we cannot use Angular Material's icon module.
- Rather, we can simple render the icon using:
<span class="material-icons">event</span>
. - Invoke the
transform()
method of the injectedDatePipe
instance.
Solution
export class GridComponent {
columnDefs = [
{
headerName: 'Date of Order',
field: 'dateOfOrder',
filter: 'agDateColumnFilter',
cellRenderer: (params) => {
if (params.value === undefined) {
return null;
}
return `
<div style="display: flex; align-items: center;">
<span class="material-icons">event</span>
${this.datePipe.transform(params.value)}
</div>
`;
},
}
] as ColDef<RowData>[];
}