我设置了一个ag-grid,并在其中放置了一系列用于单元格渲染的组件。当我的数据集加载时,垂直滚动效果很好,但除非使用触控板或启用水平滚动的鼠标,否则水平滚动并不明显。
我希望能够在网格顶部添加滚动条,并在底部添加自动生成的滚动条?
有人遇到过这个问题,提出解决方案吗?
预先感谢
答案 0 :(得分:0)
这个问题很老,但我在同一个问题上苦苦挣扎,并想出了一些可行的方法。
我的解决方案的主要思想是...
style
属性更改,以保持克隆的滚动条的大小同步以下代码适用于Angular,但概念与Vanilla JS,React或Vue相同。
首先,抓住gridReady
事件:
<ag-grid-angular
...
(gridReady)="onGridReady()">
</ag-grid-angular>
在与事件关联的函数中,使用以下代码克隆AgGrid滚动条并使滚动条保持同步:
// hold the `MutationObserver` to be disconnected when component is destroyed
private mutationObserver: MutationObserver;
onGridReady() {
// css class selectors
const headerSelector = '.ag-header';
const scrollSelector = '.ag-body-horizontal-scroll';
const scrollViewportSelector = '.ag-body-horizontal-scroll-viewport';
const scrollContainerSelector = '.ag-body-horizontal-scroll-container';
// get scrollbar elements
const scrollElement = document.querySelector(scrollSelector);
const scrollViewportElement = document.querySelector(scrollViewportSelector);
const scrollContainerElement = document.querySelector(scrollContainerSelector);
// create scrollbar clones
const cloneElement = scrollElement.cloneNode(true) as Element;
const cloneViewportElement = cloneElement.querySelector(scrollViewportSelector);
const cloneContainerElement = cloneElement.querySelector(scrollContainerSelector);
// insert scrollbar clone
const headerElement = document.querySelector(headerSelector);
headerElement.insertAdjacentElement('afterend', cloneElement);
// add event listeners to keep scroll position synchronized
scrollViewportElement.addEventListener('scroll', () => cloneViewportElement.scrollTo({ left: scrollViewportElement.scrollLeft }));
cloneViewportElement.addEventListener('scroll', () => scrollViewportElement.scrollTo({ left: cloneViewportElement.scrollLeft }));
// create a mutation observer to keep scroll size synchronized
this.mutationObserver = new MutationObserver(mutationList => {
for (const mutation of mutationList) {
switch (mutation.target) {
case scrollElement:
cloneElement.setAttribute('style', scrollElement.getAttribute('style'));
break;
case scrollViewportElement:
cloneViewportElement.setAttribute('style', scrollViewportElement.getAttribute('style'));
break;
case scrollContainerElement:
cloneContainerElement.setAttribute('style', scrollContainerElement.getAttribute('style'));
break;
}
}
});
// start observing the scroll elements for `style` attribute changes
this.mutationObserver.observe(scrollElement, { attributeFilter: ['style'], subtree: true });
}
销毁组件时,请断开MutationObserver
的连接以避免内存泄漏。
ngOnDestroy() {
// stop observing
this.mutationObserver.disconnect();
}
这很棘手,所有操作都基于使克隆的滚动条与原始滚动条保持同步,但到目前为止,它对我的用例非常有用。
祝你好运