Angular - ag-grid - 动态添加列

Angular - ag-grid - add columns dynamically

我需要在 2 种情况下向我的 Ag-grid 添加一些列。其他情况我只需要基列。

所以在构造函数中我这样声明我的网格:

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',
      }
];

然后在我的 ngOnInit 中,在某些情况下我需要向我的 ag-grid 添加列。

我尝试了以下方法:

 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

也试过

 this.gridOption.columnDefs.push({ headerName: 'Bloc', field:'block'});
 this.gridOption.columnDefs.push({ headerName: 'SDS/Hosp', field:'SDSorHosp'});

有人有想法吗? 谢谢

您不能只将新值推送到 columnDefs,我的意思是您肯定可以,但是在 ag-grid 情况下流程并不像那样工作。

所以要实现你的目标(动态add\remove columnDefs)你需要使用setColumnDefs(colDefs)方法

setColumnDefs(colDefs) Call to set new column definitions into the grid. The grid will redraw all the column headers, and then redraw all of the rows.

所以从逻辑上讲,您只需要创建新的列数组然后调用 this.gridOption.api.setColumnDefs(...)

如果您要动态添加的列是固定的,并且您希望根据某些条件 hide/unhide 这些列,您可以使用带有回调的隐藏 属性。

隐藏:真实