CDK 无限滚动结束检查

CDK Infinite scroll end checking

我正在尝试实现无限滚动,以便在用户向下滚动列表时动态地将项目加载到列表中,但是当我访问 end 和 total 时,结果是一样的,我需要检查最后一项是否是到达,然后将新项目添加到列表中。问题是 end 和 total 都是一样的,每次都会被触发

HTML

<cdk-virtual-scroll-viewport style="height: 300px" itemSize="5" (scrolledIndexChange)="nextBatch($event)">
  <li *cdkVirtualFor="let row of auditDetails; let j=index;" style="height: 100px;  box-shadow: 0 1px 1px black;">{{j}}</li>
</cdk-virtual-scroll-viewport>

TS

auditDetails = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

@ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;

ngAfterViewInit() { }

nextBatch(currIndex: number, items: any[]) {
  const start = this.viewPort.getRenderedRange().start;
  const end = this.viewPort.getRenderedRange().end;
  const total = this.viewPort.getDataLength();
  console.log(`end is ${end} total is ${total}`)
  if (end == total) {
    console.log("end reached increase page no")
  }
}

trackByIdx(i: number) {
  return i;
}

Stackblitz link https://stackblitz.com/edit/cdk-infinite-scroll-ufuewv

根据 CDK documentation itemSize 属性 以 像素 表示。我认为您试图将其表示为多个项目,这是不正确的。您应该这样尝试(itemSize 值与您的每项 100 像素的内联样式高度相匹配):

itemSize="100"

从现在开始我可以在输出日志中看到:

end is 5 total is 20
end is 5 total is 20
end is 5 total is 20
end is 7 total is 20
end is 7 total is 20
end is 9 total is 20
end is 9 total is 20
end is 9 total is 20
end is 11 total is 20
end is 13 total is 20
end is 13 total is 20
end is 15 total is 20
end is 15 total is 20
end is 17 total is 20
end is 17 total is 20
end is 17 total is 20
end is 19 total is 20
end is 20 total is 20
end reached increase page no