Reputation: 83
I'm trying to dynamically add a new row on button click event, on ag-grid on my ReactJS page.
Code below works for me, when the I've the fixed number of columns known at design-time..
let row ={
products1: "a",
products2: "b",
products3: "c"
}
gridApi.updateRowData(add: [row])
But I need to get this working as well, if the number of columns are variable and are only known at run time. Not sure if this is feasible in ReactJS/ag-grid?
Do I need to use array's map feature here?? So far, I've tried the below, but gives syntax error.
const rowArray = []
for(int index=0; index < myProductColumnsArrAtRunTime.length;index++)
{
rowArray.map((myProductColumnsArrAtRunTime[i], myProductColumnsArrAtRunTime[i].category) => {myProductColumnsArrAtRunTime[i]}: {myProductColumnsArrAtRunTime[i].category});
}
gridApi.updateRowData(add: [rowArray])
Upvotes: 0
Views: 8463
Reputation: 10161
To dynamically add a new row to the grid with variable columns use below code
Note: Here I have used functions from lodash
library which starts from _
// GET GRID colDefs
const colDefs = gridApi.getColumnDefs();
const newRowObj = {};
// LOOP OVER THE `colDefs` AND SET THE `null` DATA FOR EACH FIELD FOR THE NEWLY ADDED ROW
_.forEach(colDefs, (eachColDef) => {
const { field } = eachColDef;
_.set(newRowObj, field, null);
});
// ADD THE NEW ROW TO THE GRID
gridApi.updateRowData({
add: [newRowObj],
addIndex: 0, // YOU CAN PASS THE INDEX AT WHICH THE NEW ROW IS TO BE ADDED
});
Upvotes: 1
Reputation: 26
If the number of columns change after the initial state of the grid, you need to update the column definitions first. Refer documentation for updating column definition.
Later the 'Add row' button should add new rowData based on the new set of columns. This has to be done manually based on the different column structures you have.
Upvotes: 0