Skip to content

Commit 8140af4

Browse files
committed
Revert "Revert "perf(cdk/scrolling): do not run change detection if there are no viewChange listeners (#23987)"" (#24617)
This reverts commit d8c7c48. (cherry picked from commit 71bdb14)
1 parent 5180222 commit 8140af4

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,
@@ -786,6 +787,43 @@ describe('CdkVirtualScrollViewport', () => {
786787
}
787788
}).not.toThrow();
788789
}));
790+
791+
describe('viewChange change detection behavior', () => {
792+
let appRef: ApplicationRef;
793+
794+
beforeEach(inject([ApplicationRef], (ar: ApplicationRef) => {
795+
appRef = ar;
796+
}));
797+
798+
it('should not run change detection if there are no viewChange listeners', fakeAsync(() => {
799+
finishInit(fixture);
800+
testComponent.items = Array(10).fill(0);
801+
fixture.detectChanges();
802+
flush();
803+
804+
spyOn(appRef, 'tick');
805+
806+
viewport.scrollToIndex(5);
807+
triggerScroll(viewport);
808+
809+
expect(appRef.tick).not.toHaveBeenCalled();
810+
}));
811+
812+
it('should run change detection if there are any viewChange listeners', fakeAsync(() => {
813+
testComponent.virtualForOf.viewChange.subscribe();
814+
finishInit(fixture);
815+
testComponent.items = Array(10).fill(0);
816+
fixture.detectChanges();
817+
flush();
818+
819+
spyOn(appRef, 'tick');
820+
821+
viewport.scrollToIndex(5);
822+
triggerScroll(viewport);
823+
824+
expect(appRef.tick).toHaveBeenCalledTimes(1);
825+
}));
826+
});
789827
});
790828

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

0 commit comments

Comments
 (0)