在使用 Bootstrap Angular 选项卡时遇到了这个问题,但其他库的解决方案应该是类似的。希望这可以帮助其他仍在努力寻找解决方案的人。
- 每个 ag-grid 都需要有 onGridReady 函数。
- 显示网格的第一个选项卡在 DOM 中呈现时没有问题调整列的大小以适应它。
- 对于其他选项卡中的网格,请在选项卡更改时触发的事件中调用 sizeColumnsToFit()(对于 Bootstrap 的 selectTab)。检查其他相应库的文档。
HTML:
<tabset type="pills">
<tab heading="heading1" id="tab1">
<ag-grid-angular
class="ag-theme-balham ag-grid-table"
[rowData]="data1$ | async"
[defaultColDef]="defaultColDef"
[columnDefs]="columnDefs1"
(gridReady)="onGridReady1($event)"
>
</ag-grid-angular>
</tab>
<tab heading="heading2" id="tab2" (selectTab)="onSelect($event)">
<ag-grid-angular
class="ag-theme-balham ag-grid-table"
[rowData]="data2$ | async"
[defaultColDef]="defaultColDef"
[columnDefs]="columnDefs2"
(gridReady)="onGridReady2($event)"
>
</ag-grid-angular>
</tab>
<tabset>
打字稿:
import { Component, OnInit} from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { ColDef, GridReadyEvent } from 'ag-grid-community';
import { TabDirective } from 'ngx-bootstrap/tabs';
@Component({
selector: 'app-tabs',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css'],
})
export class TabsetComponent implements OnInit {
data1$ = new BehaviorSubject<any[]>([]);
data2$ = new BehaviorSubject<any[]>([]);
private gridApi2;
private gridColumnApi2;
defaultColDef: ColDef = {
sortable: true,
filter: true,
resizable: true,
};
columnDefs1: ColDef[] = [
{ headerName: 'Category', field: 'category' },
{ headerName: 'Name', field: 'name' },
];
columnDefs2: ColDef[] = [
{ headerName: 'Module', field: 'module' },
{ headerName: 'Approval', field: 'approvalName' },
];
constructor() {}
ngOnInit(): void {}
// Event fired on tab change, needed only for tabs that are not rendered on page laod
onSelect(event: TabDirective) {
switch (event.heading) {
case 'heading2':
return this.gridApi2.sizeColumnsToFit();
default:
return;
}
}
// tab displayed on page load can call sizeColumnsToFit() directly
onGridReady1(event: GridReadyEvent) {
event.api.sizeColumnsToFit();
}
onGridReady2(event: GridReadyEvent) {
this.gridApi2 = event.api;
this.gridColumnApi2 = event.columnApi;
}
}