Skip to content

Commit 0f42873

Browse files
committed
fix(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 f405cb6 commit 0f42873

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
@@ -100,6 +100,22 @@ describe('CdkVirtualScrollViewport', () => {
100100
.toEqual({start: 0, end: 4}, 'should render the first 4 50px items to fill 200px space');
101101
}));
102102

103+
it('should contract the rendered range when changing to less data', fakeAsync(() => {
104+
finishInit(fixture);
105+
106+
expect(viewport.getRenderedRange()).toEqual({start: 0, end: 4});
107+
108+
fixture.componentInstance.items = [0, 1];
109+
fixture.detectChanges();
110+
111+
expect(viewport.getRenderedRange()).toEqual({start: 0, end: 2});
112+
113+
fixture.componentInstance.items = [];
114+
fixture.detectChanges();
115+
116+
expect(viewport.getRenderedRange()).toEqual({start: 0, end: 0});
117+
}));
118+
103119
it('should get the rendered content offset', fakeAsync(() => {
104120
finishInit(fixture);
105121
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
@@ -277,6 +277,9 @@ export class CdkVirtualScrollViewport extends CdkScrollable implements OnInit, O
277277

278278
/** Sets the currently rendered range of indices. */
279279
setRenderedRange(range: ListRange) {
280+
// The range should never be greater than the data.
281+
range.end = Math.min(range.end, this.getDataLength());
282+
280283
if (!rangesEqual(this._renderedRange, range)) {
281284
this._renderedRangeSubject.next(this._renderedRange = range);
282285
this._markChangeDetectionNeeded(() => this._scrollStrategy.onContentRendered());

0 commit comments

Comments
 (0)