Skip to content

Commit 6076801

Browse files
committed
fix(cdk/scrolling): virtual scroll viewport returning range larger than data when switching to smaller set
Fixes the `VirtualScrollViewport.getRenderedRange` returning a range that is larger than the data when we switch to a smaller set. I decided to do this in the viewport, rather than the strategy so we don't have to repeat the same logic in each of the strategies. Fixes #19029.
1 parent 8424209 commit 6076801

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/cdk/scrolling/virtual-scroll-viewport.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,22 @@ describe('CdkVirtualScrollViewport', () => {
101101
.toEqual({ start: 0, end: 4 });
102102
}));
103103

104+
it('should contract the rendered range when changing to less data', fakeAsync(() => {
105+
finishInit(fixture);
106+
107+
expect(viewport.getRenderedRange()).toEqual({start: 0, end: 4});
108+
109+
fixture.componentInstance.items = [0, 1];
110+
fixture.detectChanges();
111+
112+
expect(viewport.getRenderedRange()).toEqual({start: 0, end: 2});
113+
114+
fixture.componentInstance.items = [];
115+
fixture.detectChanges();
116+
117+
expect(viewport.getRenderedRange()).toEqual({start: 0, end: 0});
118+
}));
119+
104120
it('should get the rendered content offset', fakeAsync(() => {
105121
finishInit(fixture);
106122
triggerScroll(viewport, testComponent.itemSize + 5);

src/cdk/scrolling/virtual-scroll-viewport.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,9 @@ export class CdkVirtualScrollViewport extends CdkScrollable implements OnInit, O
284284

285285
/** Sets the currently rendered range of indices. */
286286
setRenderedRange(range: ListRange) {
287+
// The range should never be greater than the data.
288+
range.end = Math.min(range.end, this.getDataLength());
289+
287290
if (!rangesEqual(this._renderedRange, range)) {
288291
if (this.appendOnly) {
289292
range = {start: 0, end: Math.max(this._renderedRange.end, range.end)};

0 commit comments

Comments
 (0)