Skip to content

Commit

Permalink
perf(cdk/scrolling): do not run change detection if there are no `vie…
Browse files Browse the repository at this point in the history
…wChange` listeners (angular#23987)
  • Loading branch information
arturovt authored Mar 17, 2022
1 parent ee452de commit ad33d7a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/cdk/scrolling/virtual-for-of.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,9 @@ export class CdkVirtualForOf<T>
});
this._viewport.renderedRangeStream.pipe(takeUntil(this._destroyed)).subscribe(range => {
this._renderedRange = range;
ngZone.run(() => this.viewChange.next(this._renderedRange));
if (this.viewChange.observers.length) {
ngZone.run(() => this.viewChange.next(this._renderedRange));
}
this._onRenderedDataChange();
});
this._viewport.attach(this);
Expand Down
38 changes: 38 additions & 0 deletions src/cdk/scrolling/virtual-scroll-viewport.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
ViewEncapsulation,
Directive,
ViewContainerRef,
ApplicationRef,
} from '@angular/core';
import {
waitForAsync,
Expand Down Expand Up @@ -786,6 +787,43 @@ describe('CdkVirtualScrollViewport', () => {
}
}).not.toThrow();
}));

describe('viewChange change detection behavior', () => {
let appRef: ApplicationRef;

beforeEach(inject([ApplicationRef], (ar: ApplicationRef) => {
appRef = ar;
}));

it('should not run change detection if there are no viewChange listeners', fakeAsync(() => {
finishInit(fixture);
testComponent.items = Array(10).fill(0);
fixture.detectChanges();
flush();

spyOn(appRef, 'tick');

viewport.scrollToIndex(5);
triggerScroll(viewport);

expect(appRef.tick).not.toHaveBeenCalled();
}));

it('should run change detection if there are any viewChange listeners', fakeAsync(() => {
testComponent.virtualForOf.viewChange.subscribe();
finishInit(fixture);
testComponent.items = Array(10).fill(0);
fixture.detectChanges();
flush();

spyOn(appRef, 'tick');

viewport.scrollToIndex(5);
triggerScroll(viewport);

expect(appRef.tick).toHaveBeenCalledTimes(1);
}));
});
});

describe('with RTL direction', () => {
Expand Down

0 comments on commit ad33d7a

Please sign in to comment.