Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?

 # in html xyz.commponent.tz

<tabset #staticTabs>
    <tab heading="User">
      <ag-grid-angular
        style="width: 100%; height: 500px;"
        class="ag-theme-material"
        [rowData]="rowData"
        [columnDefs]="columnDefs"
        [gridOptions]="gridOptions"
      >
      </ag-grid-angular>
    </tab>
    <tab heading="Whitelisted User" >
      <ag-grid-angular
        style="width: 100%; height: 500px;"
        class="ag-theme-material"
        [rowData]="rowData1"
        [columnDefs]="columnDefs1"
        [gridOptions]="gridOptions"
      >
      </ag-grid-angular>
    </tab>
    <tab heading="Blacklisted User">
      <ag-grid-angular
        style="width: 100%; height: 500px;"
        class="ag-theme-material"
        [rowData]="rowData2"
        [columnDefs]="columnDefs2"
        [gridOptions]="gridOptions"
      >
      </ag-grid-angular>
    </tab>

  </tabset>
#in xyz.component.ts
constructor() {
this.gridOptions = {
  onGridReady: () => {
    this.gridOptions.api.sizeColumnsToFit();
  },
};}

I want to resize all 3 ag-grid but no one is resized. it gives no error in the console but shows this ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?

like image 482
avi Avatar asked Oct 28 '25 14:10

avi


1 Answers

This has been one of the issues of ag-grid angular which was resolved in v16 when they introduced this callback - onFirstDataRendered

Try invoking resize code in onFirstDataRendered instead of onGridReady-

  onFirstDataRendered(params) {
    params.api.sizeColumnsToFit();
  }

You can also try using a small timeout while calling sizeColumnsToFit in onGridReady if you are on some older version.

As per docs -

Note that api.sizeColumnsToFit() needs to know the grid width in order to do its maths. If the grid is not attached to the DOM, then this will be unknown. In the example below, the grid is not attached to the DOM when it is created (and hence api.sizeColumnsToFit() should fail). The grid checks again after 100ms, and tries to resize again. This is needed for some frameworks (e.g. Angular) as DOM objects are used before getting attached.

Example here

like image 89
Pratik Bhat Avatar answered Oct 30 '25 15:10

Pratik Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!