Apex Grid Column Cell Template
By default, the grid uses the key of the column to render the value as a string inside the cell. This is fine for basic scenarios, but if you want to customize the rendered output or the final output is a combination of different data fields, you should use a cell template renderer.
To achieve that, set the cellTemplate property of the column.
{
cellTemplate?: (params: ApexCellContext<T, K>) => TemplateResult | unknown;
}
Use as a formatter function
For the simple scenario where some formatting is required, one can just return the formatted value. Here is an example for displaying a number value to a locale currency format:
const { format: asCurrency } = new Intl.NumberFormat('en-EN', { style: 'currency', currency: 'EUR' });
{
...
/** Return the custom currency format for a value `value = 123456.789` */
cellTemplate: (params) => asCurrency(params.value) // => "€123,456.79"
...
}
You can combine values different fields from the data source as well. Refer to the API documentation for ApexCellContext for more information.
const { format: asCurrency } = new Intl.NumberFormat('en-EN', { style: 'currency', currency: 'EUR' });
{
...
/** Return the custom currency format for an order of 10 items where the price is 99.99 */
cellTemplate: ({ value, data }) => asCurrency(value * data.count) // => "€999.90"
...
}
Custom DOM templates
Aside from using the cellTemplate property as a value formatter, you can also create your own DOM template, which will be rendered inside the cell container.
We've decided to re-use the functionality provided by lit and its tagged template syntax for building declarative DOM fragments.
You can template any standard DOM elements as well as web components from other libraries.
// Import the `html` tag function from the Lit package.
import { html } from "lit";
{
key: 'rating',
// Use another web component to represent the `rating` value in the grid
cellTemplate: ({ value }) => html`<igc-rating readonly value=${value}></igc-rating>`
...
}
Keep in mind the more complex and involved the template is, the greater the performance cost. Avoid complex DOM structures if performance is important.
Cell context object
The custom cell renderer is passed an ApexCellContext object as a parameter with the following props:
/**
* Context object for the row cell template callback.
*/
export interface ApexCellContext<
T extends object,
K extends Keys<T> = Keys<T>
> {
/**
* The cell element parent of the template. A rendered element that may
* later show another record: do not hold it across an `await`.
*/
parent: ApexGridCell<T>;
/**
* The row element containing the cell. A rendered element that may later
* show another record, as for `parent`.
*/
row: ApexGridRow<T>;
/**
* The record this cell was rendered for. Stays the same record for the
* life of this context object.
*/
readonly data: T;
/**
* The current configuration for the column.
*/
column: ColumnConfiguration<T, K>;
/**
* The value from the data source for this cell.
*/
value: PropertyType<T, K>;
/**
* Commits a new value for this cell without entering edit mode. Available
* when the column is editable. Writes to `data`.
*/
commit?: (value: PropertyType<T, K>) => Promise<boolean>;
}
Row recycling
Body rows are recycled by default (rowRecycling): a scroll, sort or filter re-binds the rendered row elements to the records now in view instead of building new rows, which makes long jumps and sorts cheaper on large grids. A row element and its cells can therefore show another record later, so a template should:
- derive everything it renders from its context on each render,
- read the record from
ctx.data, notctx.row, and not holdctx.roworctx.parentacross anawait, - keep no state in the elements it creates, or wrap itself in Lit's
keyeddirective so the state is rebuilt per record.
import { html } from 'lit';
import { keyed } from 'lit/directives/keyed.js';
{
key: 'status',
cellTemplate: (ctx) => keyed(ctx.data, html`<my-status-widget .value=${ctx.value}></my-status-widget>`),
}
Expensive components: update in place
For an ApexCharts chart in each row, use the chart column type (4.1.0): it does what this section describes. The pattern below is for other expensive components.
keyed is right for a cheap widget. For an expensive one, such as a chart, it means building a new instance every time a row shows a record it did not have: with an ApexCharts chart in each of 1,000 rows, one scroll down and back built 3,011 charts and ran 14 to 17 long tasks. Keep one instance per element instead, and point it at the new record when the property changes:
class RowChart extends HTMLElement {
set record(r) {
this._record = r;
this.chart?.updateSeries([{ data: r.trend }], false); // recycled: re-point, do not rebuild
}
connectedCallback() {
if (this.chart) return; // a move, not a new row
this.chart = new ApexCharts(this, options(this._record));
this.chart.render();
}
disconnectedCallback() {
// A scroll step moves row elements, which disconnects and reconnects them.
queueMicrotask(() => {
if (this.isConnected || !this.chart) return;
this.chart.destroy();
this.chart = null;
});
}
}
// cellTemplate: (ctx) => html`<row-chart .record=${ctx.data}></row-chart>`
Two things make this necessary. A sort re-binds rows in place without reconnecting anything, so a component that reads its data only in connectedCallback keeps the old record. And on a scroll step the grid moves the row before it assigns the new record, so a moved element reconnects still holding the previous one (apex-grid#39). Across one scroll over 1,000 rows, 1,217 of 1,232 disconnects were moves, so tear-down belongs behind the isConnected check above. The chart in every grid row recipe has the measurements and the accessible-name side.
ctx.commit writes to ctx.data, so a commit issued after an await still lands on the record the cell was rendered for. Editor templates receive the same data field, but an editor's commit is not bound to it: it commits whichever cell is in edit when it is called, so do not call it after an await that can outlive the edit.
For templates that must keep element state across a sort or a move, such as some third-party widgets, turn recycling off and each row element stays with its record:
grid.rowRecycling = false;
<apex-grid row-recycling="false"></apex-grid>
Detail panel content follows its record and keeps its DOM state either way.