Динамическое добавление столбцов в ag-grid из HTTP-запроса - PullRequest
0 голосов
/ 30 мая 2020

Я пытаюсь динамически добавлять столбцы в аг-сетку в зависимости от ответа на HTTP-запрос.

фиксированные столбцы:

 rowData: Task[];
 gridOptions: GridOptions;
 domLayout = "autoHeight";

 columnDefs = [
   { headerName: 'Titre', field: 'name', sortable: true, filter: true, width: 120 },
   { headerName: 'Collaborateur', field: 'collaborator', sortable: true, width: 250 },
   { headerName: 'Statut', field: 'status', sortable: true, width: 100 },
   { headerName: 'Lot', field: 'lot', sortable: true, width: 100 },
 ]

А затем в зависимости от HTTP-ответа Я хотел бы добавить такие новые столбцы, как эта

{
  headerName: 'IC S1', valueGetter: function (params) { return params.data.charge[0] },
  editable: true, sortable: true, width: 60
},

Я знаю, что делаю что-то не так, но не знаю, что именно. Вот что я пытаюсь:

colDef = [];
newColumns() {
 this.rowData.forEach(task => {
  task.charge.forEach(initCharge => {

    let i = 0;
    this.colDef.push({ headerName: 'IC S' + (i + 1), field: 'initCharge', })
    });
  this.gridOptions.api.setColumnDefs(this.colDef);
  });
}

И все это я вызываю в ngOnInit

 ngOnInit() {
   this.subscription = this.route.params.subscribe(params => {
      this.id = +params['id'];
   });

   this.getProjectTasks();
   this.newColumns();
   this.getDates();
 }

1 Ответ

0 голосов
/ 30 мая 2020

Вот как я решил проблему, хотя и не был уверен, что это лучше всего.

 getProjectTasks() {
this.managerService.getTasksByProject(this.id).subscribe((resp) => {
  this.rowData = resp;
  let maxCharge = 0;
  this.rowData.forEach(task => {
    if (task.charge.length > maxCharge) {
      maxCharge = task.charge.length
    }
  });

  for (let i = 1; i < maxCharge; i++) {
    let j = i + 1;
    this.columnDefs.push({
      headerName: 'IC S' + j, valueGetter: function (params) { return params.data.charge[i] }, valueSetter: function (params) {
        if (params.data.charge[i] === params.newValue) {
          return false
        } else { params.data.charge[i] = params.newValue; return true }
      }, editable: true, sortable: true, maxWidth: 200
    })
  }

  this.gridOptions.api.setColumnDefs(this.columnDefs);
  this.gridOptions.api.sizeColumnsToFit();
},
  (err) => {
    console.log(err);
    }
  );
}
...