Skip to content

Commit 71bdb14

Browse files
authored
Revert "Revert "perf(cdk/scrolling): do not run change detection if there are no viewChange listeners (#23987)"" (#24617)
This reverts commit d8c7c48.
1 parent 1bc98ec commit 71bdb14

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/cdk/scrolling/virtual-for-of.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,9 @@ export class CdkVirtualForOf<T>
199199
});
200200
this._viewport.renderedRangeStream.pipe(takeUntil(this._destroyed)).subscribe(range => {
201201
this._renderedRange = range;
202-
ngZone.run(() => this.viewChange.next(this._renderedRange));
202+
if (this.viewChange.observers.length) {
203+
ngZone.run(() => this.viewChange.next(this._renderedRange));
204+
}
203205
this._onRenderedDataChange();
204206
});
205207
this._viewport.attach(this);

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
ViewEncapsulation,
1616
Directive,
1717
ViewContainerRef,
18+
ApplicationRef,
1819
} from '@angular/core';
1920
import {
2021
waitForAsync,
@@ -802,6 +803,43 @@ describe('CdkVirtualScrollViewport', () => {
802803
}
803804
}).not.toThrow();
804805
}));
806+
807+
describe('viewChange change detection behavior', () => {
808+
let appRef: ApplicationRef;
809+
810+
beforeEach(inject([ApplicationRef], (ar: ApplicationRef) => {
811+
appRef = ar;
812+
}));
813+
814+
it('should not run change detection if there are no viewChange listeners', fakeAsync(() => {
815+
finishInit(fixture);
816+
testComponent.items = Array(10).fill(0);
817+
fixture.detectChanges();
818+
flush();
819+
820+
spyOn(appRef, 'tick');
821+
822+
viewport.scrollToIndex(5);
823+
triggerScroll(viewport);
824+
825+
expect(appRef.tick).not.toHaveBeenCalled();
826+
}));
827+
828+
it('should run change detection if there are any viewChange listeners', fakeAsync(() => {
829+
testComponent.virtualForOf.viewChange.subscribe();
830+
finishInit(fixture);
831+
testComponent.items = Array(10).fill(0);
832+
fixture.detectChanges();
833+
flush();
834+
835+
spyOn(appRef, 'tick');
836+
837+
viewport.scrollToIndex(5);
838+
triggerScroll(viewport);
839+
840+
expect(appRef.tick).toHaveBeenCalledTimes(1);
841+
}));
842+
});
805843
});
806844

807845
describe('with RTL direction', () => {

0 commit comments

Comments
 (0)