我正在尝试使用CDK虚拟滚动条对项目列表实施无限循环滚动滚动
我到了放弃的地步。我无法实现,如何实现CDK虚拟滚动?
这是我的代码
import { Component, ViewChild, ChangeDetectionStrategy } from '@angular/core';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { Observable, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'my-app',
template: `
<ng-container *ngIf="infinite | async; let items">
<cdk-virtual-scroll-viewport itemSize="50"
(scrolledIndexChange)="nextBatch($event, (items[items.length - 1].index))">
<div *cdkVirtualFor="let item of items; trackBy: trackByIdx">{{item}}</div>
</cdk-virtual-scroll-viewport>
</ng-container>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
arr = Array.from({ length: 10 }).map((_, i) => `Item #${i}`);
offset = new BehaviorSubject<any>({ offset: 0 });
infinite: Observable<any[]>;
@ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;
constructor() {
this.infinite = this.offset.pipe(
map((n: any) => this.getBatch(n)),
);
}
getBatch({ offset, loadPrev, loadNext, e }) {
let arr = [...this.arr];
if (loadPrev) {
const last = arr[arr.length - 1];
return [last, ...arr];
}
if (loadNext) {
const first = arr[0];
return [...arr, first];
}
return arr;
}
nextBatch(e, offset) {
const end = this.viewPort.getRenderedRange().end;
const start = this.viewPort.getRenderedRange().start;
const total = this.viewPort.getDataLength();
if (start === 0) {
this.offset.next({ offset: offset, loadPrev: true, e });
}
if (end === total) {
this.offset.next({ offset: offset, loadNext: true, e });
}
}
trackByIdx(i) {
return i;
}
}
答案 0 :(得分:1)
我们只需要检查滚动是否滚动到最后一项,然后再滚动回到第一项。例如:
app.component.html
<cdk-virtual-scroll-viewport class="example-viewport" [itemSize]="itemSize" (scrolledIndexChange)="onScroll($event)">
<div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>
app.component.ts
items = Array.from({ length: 100 }).map((_, i) => `Item #${i}`);
itemSize = 5;
@ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;
onScroll(event) {
console.log(event);
if( event >= ((this.items.length-this.itemSize-1)*10) ) {
this.viewPort.scrollToIndex(0);
}
}
答案 1 :(得分:0)
cdk-virtual-scroll-viewport必须具有高度,并且其循环播放的项目也应具有固定的高度。组件需要此信息来计算何时应呈现或删除项目。
例如
cdk-virtual-scroll-viewport {
height: 100vh;
li {
height: 100px;
}
}