rod*_*_la 8 angular angular-cdk-virtual-scroll
使用cdk虚拟视口时,需要设置视口的高度
.example-viewport {
height: 800px;
width: 100%;
border: 1px solid black;
}
<cdk-virtual-scroll-viewport class="example-viewport">
<div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>
Run Code Online (Sandbox Code Playgroud)
但我希望 cdk-virtual-scroll-viewport 如果未达到出现滚动条的最大高度,则将其包装起来。但视口不适用于最大高度。
如果没有水平滚动条,则视口将高度设置为最大高度即可。但在我当前的设计用户界面中,我需要显示水平滚动条,因为有很多内容列,如下图所示。
然后由于视口的高度,滚动条远远低于。行项目会随着时间的推移而增加,但在项目增加到最大高度之前,我希望水平滚动条换行到内容高度,但目前似乎无法实现。
我不使用 mat-table 的原因是我想支持无限滚动并渲染适合屏幕的项目。Mat-table 不支持这一点,如果我继续向下滚动并请求数据,模板中的行项会增加并影响性能。
有人有更好的建议吗?
多谢。
我得到了一个修复,它考虑列表中的元素数量来设置容器高度。它计算容器的高度,直到达到最终高度值。请按照以下步骤操作并告诉我。
cdk-virtual-scroll-viewport1.在你的组件中保留一个引用我们需要它能够checkViewportSize稍后调用并使 CdkVirtualScrollViewport 重新计算其内部大小。
成分
@ViewChild('scrollViewport')
private cdkVirtualScrollViewport;
Run Code Online (Sandbox Code Playgroud)
模板
<cdk-virtual-scroll-viewport class="example-viewport" #scrollViewport>
...
</cdk-virtual-scroll-viewport>
Run Code Online (Sandbox Code Playgroud)
height2.根据列表中元素的个数计算列表容器成分
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`;
}
Run Code Online (Sandbox Code Playgroud)
模板
<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>
Run Code Online (Sandbox Code Playgroud)
应该是全部了。您只需根据您的情况调整该函数即可获得您期望的结果itemHeight。visibleItems