Angular-Ag-Grid - Dynamically add columns
Helen
In 2 cases, I need to add some columns to Ag-grid. In other cases, I just need the base column.
So in the constructor, I declare the grid like this:
this.gridOption.columnDefs = [
{
headerName: 'Admission date',
field: 'admissionPlannedDate',
cellRendererFramework: DateCellRendererComponent,
cellRendererParams: (params) => {
return (params.data.admissionPlannedDate ? {dateFormat: 'dd.MM.yyyy - HH:mm'} : {dateFormat: ' '});
},
cellStyle: function (params) {
return (params.data.admissionPlannedDate < new Date() ? {color: 'red'} : {});
}
},
{
headerName: 'Lastname',
field: 'lastName',
cellStyle: function (params) {
return (params.data.edsId === null ? {color: 'orange'} : {});
}
},
},
{
headerName: 'Sex',
field: 'sex',
},
{
headerName: 'Birthdate',
field: 'birthDate',
cellRendererFramework: DateCellRendererComponent,
cellRendererParams: (params) => {
return (params.data.birthDate ? {dateFormat: 'dd.MM.yyyy'} : {dateFormat: ' '});
},
},
{
headerName: 'Localisation',
field: 'localisation',
}
];
Then in my ngOnInit, in some cases, I need to add columns to my ag-grid.
I have tried the following:
this.gridOption.columnDefs.push(
{
headerName: 'Block',
field: 'block',
}, {
headerName: 'SDS/Hosp',
field: 'sdsOrHosp'
}
);
console.log(this.gridOption); //I see the new columns here so the add worked but i don't see them visual in my grid
also tried
this.gridOption.columnDefs.push({ headerName: 'Bloc', field:'block'});
this.gridOption.columnDefs.push({ headerName: 'SDS/Hosp', field:'SDSorHosp'});
Does anyone have an idea? thanks
non-nail
You can't just push the new value to columnDefs
, I mean you can, but the flow can't be the ag-grid
case.
So to achieve your goal (add\remove dynamically columnDefs
) you need to use the methodsetColumnDefs(colDefs)
setColumnDefs(colDefs)
Called to set a new column definition in the grid. The grid will redraw all column headers and then all rows.
So logically you just need to create new column array and then callthis.gridOption.api.setColumnDefs(...)