我得到了一个修复,它考虑了列表中的元素数量来设置容器高度。它计算容器的高度量,直到它达到最终高度值。请按照以下步骤告诉我。
cdk-virtual-scroll-viewport
1.在您的组件中保留参考
我们需要它能够checkViewportSize
稍后调用并使 CdkVirtualScrollViewport 重新计算其内部大小。
零件
@ViewChild('scrollViewport')
private cdkVirtualScrollViewport;
模板
<cdk-virtual-scroll-viewport class="example-viewport" #scrollViewport>
...
</cdk-virtual-scroll-viewport>
height
2.根据列表元素个数计算列表容器
零件
calculateContainerHeight(): string {
const numberOfItems = this.items.length;
// This should be the height of your item in pixels
const itemHeight = 20;
// The final number of items you want to keep visible
const visibleItems = 10;
setTimeout(() => {
// Makes CdkVirtualScrollViewport to refresh its internal size values after
// changing the container height. This should be delayed with a "setTimeout"
// because we want it to be executed after the container has effectively
// changed its height. Another option would be a resize listener for the
// container and call this line there but it may requires a library to detect
// the resize event.
this.cdkVirtualScrollViewport.checkViewportSize();
}, 300);
// It calculates the container height for the first items in the list
// It means the container will expand until it reaches `200px` (20 * 10)
// and will keep this size.
if (numberOfItems <= visibleItems) {
return `${itemHeight * numberOfItems}px`;
}
// This function is called from the template so it ensures the container will have
// the final height if number of items are greater than the value in "visibleItems".
return `${itemHeight * visibleItems}px`;
}
模板
<div [style.height]="calculateContainerHeight()">
<cdk-virtual-scroll-viewport class="example-viewport" #scrollViewport>
<div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>
</div>
这应该是全部。您只需要根据您的情况在函数中进行调整itemHeight
即可visibleItems
获得您期望的结果。