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?

Viewed 3335
 # 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?

2 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

Old thread, but the current answer didn't help me and I found this via a google search.

I had the same issue using angular material tabs. First tab was fine, but subsequent tabs failed to call sizeColumnsToFit since they were not visible in DOM until the tab is selected.

I tried various grid events such as viewportChanged, firstDataRendered, etc... but nothing worked. I ended up calling sizeColumnsToFit() within the child component after the tab was selected. There are a number of ways to do that, but I chose to use an observable to update what tab was selected and then trigger the api.sizeColumnsToFit().

Related