Normally I simply use the gridReady event, get the api and call sizeColumnsToFit().
export class MyGridApplicationComponent {
private gridOptions: GridOptions;
private showGrid2: false;
constructor() {
this.gridOptions = <GridOptions>{
onGridReady: this.gridReady.bind(),
....
};
}
gridReady(params) {
params.api.sizeColumnsToFit();
}
....
However, I have a grid that is in a hidden tab and so when the gridReady event is called, the width is 0 (get the message in the console: "tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?").
<h2>Grid only visible after button click</h2>
<button (click)="showGrid2 = true;">Show grid</button><br/><br/>
<div style="width: 100%;" [hidden]="!showGrid2">
<ag-grid-angular #agGrid2 style="width: 100%; height: 200px;" class="ag-theme-fresh" [gridOptions]="gridOptions">
</ag-grid-angular>
</div>
Is there an event I can hook into when the ag-grid becomes visible so I can resize/fit it? I've tried a few vaguely relevant events (gridSizeChanged, firstDataRendered, columnVisible, columnResized) to no avail.
I have a simplified repro in StackBlitz.
[EDIT] I tried a modification to @antirealm's suggestion below (seeing if *ngIf on the parent div made the difference) and this worked for my (over)simplified version of the problem: see StackBlitz repro.
This is all in context of a nested tabs component, where the ag-grid is not on the first tab. I've tried using *ngIf in the div containing the nested tab content:
<div *ngIf="hasBeenActive" [hidden]="!active"><ng-content></ng-content></div>
and even though the DOM shows that the ag-grid is not there, the ag-grid's gridReady event is still called before the second tab has been selected. See Stackblitz repro.
*ngIfon the grid component that becomes true when the tab is selected. In some cases you want the grid to stay there after it was created and not have to create each time, so you'd use something like*ngIf="tabSelected || tabHasBeenSelectedBefore". You'd have to set that second variable to true upon selecting the tab for the first time. - antirealm