因此,在 @phucnh 的帮助和谷歌搜索之后,我能够生成允许 TurboTable 采用其所有父大小并正确显示/隐藏滚动条的代码:
https://stackblitz.com/edit/primeng-scrollable-table-fit-parent
基本上,它包含两个 hack:
1)我们需要观察父尺寸的变化,并通过这段代码强制Angular重新评估“scrollHeight”:
ngAfterViewInit(): void {
new ResizeObserver(() => this.zone.run(() => this.onResize()))
.observe(this.container.nativeElement);
}
private onResize(): void {
// HACK: mark "scrollHeight" dirty, so it's re-evaluated.
if (this.table.scrollHeight.endsWith(' ')) {
this.table.scrollHeight = this.table.scrollHeight.slice(0, -1);
} else {
this.table.scrollHeight += ' ';
}
}
2) 为了解决在滚动条出现/消失时标题单元格不对齐的问题,我们需要进行一些肮脏的修改(受https://stackblitz.com/edit/primeng-dynamic-scrollable 启发):
// HACK: automatically re-align table header when resized. Borrowed the idea from https://stackblitz.com/edit/primeng-dynamic-scrollable
const scrollableViewNgAfterViewInit = ScrollableView.prototype.ngAfterViewInit;
ScrollableView.prototype.ngAfterViewInit = function() {
scrollableViewNgAfterViewInit.call(this);
new ResizeObserver(() => {
this.alignScrollBar();
}).observe(this.scrollBodyViewChild.nativeElement);
};
成功了。
更新(2020 年 6 月 6 日):
最近,此解决方法的第 2 部分停止工作。我假设发生这种情况是因为 Angular 现在缓存了指向生命周期事件的指针。因此,覆盖它们什么都不做,并且被覆盖的方法不会被触发。
// HACK: automatically re-align table header when resized. Borrowed the idea from https://stackblitz.com/edit/primeng-dynamic-scrollable
const bindEventsOriginal = ScrollableView.prototype.bindEvents;
ScrollableView.prototype.bindEvents = function (): void {
bindEventsOriginal.call(this);
new ResizeObserver(() => {
this.alignScrollBar();
}).observe(this.scrollBodyViewChild.nativeElement);
};
此外,PrimeNG 9.1.0 版添加了 scrollHeight="flex" ,这基本上使此解决方法的第 1 部分变得不必要。