大小列在可见时适合隐藏的 ag-grid

Size columns to fit on hidden ag-grid when becomes visible

通常我只是使用 gridReady 事件,获取 api 并调用 sizeColumnsToFit()。

export class MyGridApplicationComponent {
    private gridOptions: GridOptions;
    private showGrid2: false;

    constructor() {
        this.gridOptions = <GridOptions>{
          onGridReady: this.gridReady.bind(),
          ....
        };
    }
    gridReady(params) {
      params.api.sizeColumnsToFit();
    }
    ....

但是,我有一个隐藏选项卡中的网格,因此当调用 gridReady 事件时,宽度为 0(在控制台中获取消息:"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>

当 ag-grid 变得可见时,是否有我可以挂钩的事件,以便我可以 resize/fit 它?我已经尝试了一些模糊相关的事件(gridSizeChanged、firstDataRendered、columnVisible、columnResized)但无济于事。

我有一个简化的repro in StackBlitz

[编辑] 我尝试修改下面@antirealm 的建议(查看父 div 上的 *ngIf 是否有所不同),这对我的(过度)简化版本的问题有效:见 StackBlitz repro

这一切都在嵌套选项卡组件的上下文中,其中 ag-grid 不在第一个选项卡上。我尝试在包含嵌套选项卡内容的 div 中使用 *ngIf:

<div *ngIf="hasBeenActive" [hidden]="!active"><ng-content></ng-content></div>

即使 DOM 显示 ag-grid 不存在,ag-grid 的 gridReady 事件仍会在选择第二个选项卡之前调用。参见 Stackblitz repro

  1. Solution to original over-simplified problem:
<div *ngIf="hasBeenShown" style="width: 100%;" [hidden]="!grid2Showing">  
  <ag-grid-angular #agGrid2 style="width: 100%; height: 200px;" class="ag-theme-fresh" [gridOptions]="gridOptions">
  </ag-grid-angular>
</div>
  1. 实际问题的解决方案:ag-grid 在投影内容 (ng-content) 时命中 gridReady,在本例中是在嵌套选项卡组件中:

    a) (Solution from @antirealm) 在 nested-tab 组件上创建一个公开可用的 'hasBeenActive' 变量,然后在您的 ag-grid 上直接在 *ngIf 中使用它:

export class NestedTabComponent ... {
  ...
  public hasBeenActive: boolean = false;

  activate() {
    this.active = true;
    this.hasBeenActive = true; 
  }
  ....
<nested-tab title="Second grid" #myTab>
  <div style="width: 100%;">
    <ag-grid-angular *ngIf="myTab.hasBeenActive"
      ...>
    </ag-grid-angular>
  </div>    
</nested-tab>

b) 修改嵌套选项卡组件 to use a template(如果存在),然后将不应立即初始化的任何嵌套选项卡的内容包装在模板中:

@Component({
    selector: 'nested-tab',
    template: `
    <div *ngIf="hasBeenActive" [hidden]="!active">
      <ng-container *ngTemplateOutlet="content"></ng-container>
      <ng-content></ng-content>
    </div>`
})
export class NestedTabComponent implements OnInit {
    @ContentChild(TemplateRef) content;
    ....
<nested-tab title="Second grid">
  <ng-template>
    <p>The Second grid rendered:</p>
    <div style="width: 100%;">      
      <ag-grid-angular ...></ag-grid-angular>
    </div>    
  </ng-template> 
</nested-tab>