调整 ag-Grid 的大小(更改浏览器窗口的大小)并在两个选项卡之间切换时收到以下警告:
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?
我在 Stackblitz 中重现了这种情况:
https://angular-jpmxjy.stackblitz.io/
这是测试应用程序的组成:
组件: delleverancer.component 和leverancer.component。
您将在 chrome 开发工具中看到警告错误,
当您调整网格大小并在 tabMenu 'Leverancer' 和 'Delleverancer' 之间切换时。
你可以在这里看到代码:
https://stackblitz.com/edit/angular-jpmxjy
如何删除这个不需要的警告错误?
最佳答案
这类错误通常意味着您的应用程序中存在内存泄漏。
查看您的代码后,我注意到您如何订阅 window:resize
事件
window.addEventListener("resize", function () { ...
您应该知道,即使在组件被销毁后,此订阅仍然存在。
你可以写
removeEventListener
在 ngOnDestroy
钩。但是为此,您必须保留对原始附加功能的引用。更好的方法是使用专用的 Angular @HostListener
负责 removeEventListener
的装饰师在钩子(Hook)下:@HostListener('window:resize')
onResize() {
if (!this.gridApi) return;
setTimeout(() => {
this.gridApi.sizeColumnsToFit();
});
}
Forked Stackblitz
为了不重复自己,您可以创建如下指令:
ag-grid-resize.directive.ts
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[ag-grid-resize]'
})
export class AgGridResizeDirective {
private gridApi;
@HostListener('window:resize')
onResize() {
if (!this.gridApi) return;
setTimeout(() => {
this.gridApi.sizeColumnsToFit();
});
}
@HostListener('gridReady', ['$event'])
onGridReady(params) {
this.gridApi = params.api;
params.api.sizeColumnsToFit();
}
}
现在,您需要添加该行为就是向您的网格添加属性:
<ag-grid-angular
...
ag-grid-resize <============
>
</ag-grid-angular>
Stackblitz Example
关于angular - 在两个单独的 ag-Grid 上使用 ag-Grid 的 sizeColumnsToFit() 时出现警告 'grid zero width',由选项卡菜单显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54038024/