默认情况下,在ag-grid中自动调整列大小

时间:2019-12-10 14:16:02

标签: angular ag-grid ag-grid-angular

我尝试使用AG-Grid和angular框架默认设置自动调整大小的列。因此我将gridColumnApi.autoSizeColumns与click事件一起使用,效果很好。但是当我尝试将this.autoSizeAll()与ngOnInit()结合使用来默认设置自动调整大小列时,我会收到此错误无法读取属性'getAllColumns'

我不知道在没有单击按钮的情况下默认情况下自动调整列大小的最佳方法是什么?

<button (click)="autoSizeAll(false)">Auto-Size All</button>

<ag-grid-angular
    style="width: 900px; height: 700px;"
    class="ag-theme-balham"
    [rowData]="rowData"
    [defaultColDef]="defaultColDef"
    [columnDefs]="columnDefs"
    (firstDataRendered)="onFirstDataRendered($event)"
    (gridReady)="onGridReady($event)">
</ag-grid-angular>



ngOnInit(){
  this.autoSizeAll();
}

autoSizeAll() {

  const allColumnIds = [];
  // tslint:disable-next-line:only-arrow-functions
  this.gridColumnApi.getAllColumns().forEach(function(column) {
    allColumnIds.push(column.colId);
  });
  this.gridColumnApi.autoSizeColumns(allColumnIds);
}

onGridReady(params) {

  this.gridApi = params.api;
  this.gridColumnApi = params.columnApi;
  this.http
    .get(
      'https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinnersSmall.json'
    )
    .subscribe(data => {
      this.rowData = data;
    });
}
}

这是plunker

1 个答案:

答案 0 :(得分:1)

您正在调用该函数,甚至尚未初始化gridColumnApi。初始化this.autoSizeAll()后,尝试在onGridReady函数中调用this.gridColumnApi

onGridReady(params) {

  this.gridApi = params.api;
  this.gridColumnApi = params.columnApi;
  this.autoSizeAll();  // do your autosizing here
  this.http
    .get(
      'https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinnersSmall.json'
    )
    .subscribe(data => {
      this.rowData = data;
    });
}