# Dynamic cells
Sometimes it is necessary to change the appearance or the content of the cell depending on the row data or the row state.
One way to do this is to write a conditional cell template with if ... then ...
constructs.
However it is often more efficient just to modify cell context and/or dynamically select a cell template using row
event.
The row model includes cells
property which allows modifying cell contexts or creating cells dynamically based on row data.
# Calculated values
You should put a key attribute into the column descriptor, which you can later use to assign cell value or cell context object:
const columns = [
{ header: 'Col 1', format: 'money', key: 'custom1' },
{ header: 'Col 2', key: 'custom2' }
];
function onRow(row){
// simple syntax - just assign a value (cannot be an object)
if (row.data.id == '...'){
row.cells.custom1 = 123;
}
// assign a context object
if (row.data.something == '...'){
row.cells.custom2 = {
value: 'ABC',
style: { color: 'red' },
template: 'my-cell-tpl'
};
}
}
If you omit the key
, the field
attibute will be used instead.
# Classes/Styles
You can just modify the cell style (or css class) based on cell value or some other row data:
const columns = [
{ field: 'balance' } // if the key is missing, key = field
];
function onRow(row){
if (row.data.balance < 0){
row.cells.balance = {style: {color: 'red'}};
}
}
# Templates
It is also possible to select cell template on the fly.
const columns = [
{ field: 'something' }
];
function onRow(row){
if (row.data.something == 123){
row.cells.something = {template: 'my-custom-cell'};
}
}