Gathering detailed insights and metrics for @iharbeck/ngx-virtual-scroller
Gathering detailed insights and metrics for @iharbeck/ngx-virtual-scroller
Gathering detailed insights and metrics for @iharbeck/ngx-virtual-scroller
Gathering detailed insights and metrics for @iharbeck/ngx-virtual-scroller
Virtual Scroll displays a virtual, "infinite" list.
npm install @iharbeck/ngx-virtual-scroller
97.2
Supply Chain
100
Quality
77.7
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
49 Stars
448 Commits
31 Forks
8 Watching
19 Branches
1 Contributors
Updated on 29 Nov 2024
Minified
Minified + Gzipped
TypeScript (100%)
Cumulative downloads
Total Downloads
Last day
-3.5%
4,009
Compared to previous day
Last week
-8.2%
21,123
Compared to previous week
Last month
5%
91,192
Compared to previous month
Last year
105.4%
922,043
Compared to previous year
1
1
Virtual Scroll displays a virtual, "infinite" list. Supports horizontal/vertical, variable heights, & multi-column.
This module displays a small subset of records just enough to fill the viewport and uses the same DOM elements as the user scrolls. This method is effective because the number of DOM elements are always constant and tiny irrespective of the size of the list. Thus virtual scroll can display an infinitely growing list of items in an efficient way.
v3.0.0
Several deprecated properties removed (see changelog).
v2.1.0
Dependency Injection syntax was changed.v1.0.6
viewPortIndices API property removed. (use viewPortInfo instead)v1.0.3
Renamed everything from virtual-scroll to virtual-scroller and from virtualScroll to virtualScrollerv0.4.13
resizeBypassRefreshTheshold renamed to resizeBypassRefreshThreshold (typo)v0.4.12
The start and end values of the change/start/end events were including bufferAmount, which made them confusing. This has been corrected.
v0.4.4
The value of IPageInfo.endIndex wasn't intuitive. This has been corrected. Both IPageInfo.startIndex and IPageInfo.endIndex are the 0-based array indexes of the items being rendered in the viewport. (Previously Change.EndIndex was the array index + 1)Note - API methods marked (DEPRECATED) will be removed in the next major version. Please attempt to stop using them in your code & create an issue if you believe they're still necessary.
<thead>
on <table>
elements.IPageInfo
listeners)[checkResizeInterval]="0"
useMarginInsteadOfTranslate
flag. Defaults to false. This can affect performance (better/worse depending on your circumstances), and also creates a workaround for the transform+position:fixed browser bug.Preferred option:
1<virtual-scroller #scroll [items]="items"> 2 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 3 </my-custom-component> 4</virtual-scroller>
option 2: note: viewPortItems must be a public field to work with AOT
1<virtual-scroller [items]="items" (vsUpdate)="viewPortItems = $event"> 2 <my-custom-component *ngFor="let item of viewPortItems"> 3 </my-custom-component> 4</virtual-scroller>
option 3: note: viewPortItems must be a public field to work with AOT
1<div virtualScroller [items]="items" (vsUpdate)="viewPortItems = $event"> 2 <my-custom-component *ngFor="let item of viewPortItems"> 3 </my-custom-component> 4</div>
Step 1: Install ngx-virtual-scroller
1npm install ngx-virtual-scroller
Step 2: Import virtual scroll module into your app module
1....
2import { VirtualScrollerModule } from 'ngx-virtual-scroller';
3
4....
5
6@NgModule({
7 ...
8 imports: [
9 ....
10 VirtualScrollerModule
11 ],
12 ....
13})
14export class AppModule { }
Step 3: Wrap virtual-scroller tag around elements;
1<virtual-scroller #scroll [items]="items"> 2 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 3 </my-custom-component> 4</virtual-scroller>
You must also define width and height for the container and for its children.
1virtual-scroller { 2 width: 350px; 3 height: 200px; 4} 5 6my-custom-component { 7 display: block; 8 width: 100%; 9 height: 30px; 10}
Step 4: Create my-custom-component
component.
my-custom-component
must be a custom angular component, outside of this library.
Child component is not necessary if your item is simple enough. See below.
1<virtual-scroller #scroll [items]="items"> 2 <div *ngFor="let item of scroll.viewPortItems">{{item?.name}}</div> 3</virtual-scroller>
1interface IPageInfo { 2 startIndex: number; 3 endIndex: number; 4 scrollStartPosition: number; 5 scrollEndPosition: number; 6 startIndexWithBuffer: number; 7 endIndexWithBuffer: number; 8 maxScrollPosition: number; 9}
In alphabetical order:
Attribute | Type & Default | Description |
---|---|---|
bufferAmount | number enableUnequalChildrenSizes ? 5 : 0 | The number of elements to be rendered above & below the current container's viewport. Increase this if enableUnequalChildrenSizes isn't working well enough. |
checkResizeInterval | number 1000 | How often in milliseconds to check if virtual-scroller (or parentScroll) has been resized. If resized, it'll call Refresh() method |
compareItems | Function === comparison | Predicate of syntax (item1:any, item2:any)=>boolean which is used when items array is modified to determine which items have been changed (determines if cached child size measurements need to be refreshed or not for enableUnequalChildrenSizes ). |
enableUnequalChildrenSizes | boolean false | If you want to use the "unequal size" children feature. This is not perfect, but hopefully "close-enough" for most situations. |
executeRefreshOutsideAngularZone | boolean false | Disables full-app Angular ChangeDetection while scrolling, which can give a performance boost. Requires developer to manually execute change detection on any components which may have changed. USE WITH CAUTION - Read the "Performance" section below. |
horizontal | boolean false | Whether the scrollbars should be vertical or horizontal. |
invalidateAllCachedMeasurements | Function | ()=>void - to force re-measuring all cached item sizes. If enableUnequalChildrenSizes===false , only 1 item will be re-measured. |
invalidateCachedMeasurementAtIndex | Function | (index:number)=>void - to force re-measuring cached item size. |
invalidateCachedMeasurementForItem | Function | (item:any)=>void - to force re-measuring cached item size. |
items | any[] | The data that builds the templates within the virtual scroll. This is the same data that you'd pass to ngFor . It's important to note that when this data has changed, then the entire virtual scroll is refreshed. |
modifyOverflowStyleOfParentScroll | boolean true | Set to false if you want to prevent ngx-virtual-scroller from automatically changing the overflow style setting of the parentScroll element to 'scroll'. |
parentScroll | Element / Window | Element (or window), which will have scrollbar. This element must be one of the parents of virtual-scroller |
refresh | Function | ()=>void - to force re-rendering of current items in viewport. |
RTL | boolean false | Set to true if you want horizontal slider to support right to left script (RTL). |
resizeBypassRefreshThreshold | number 5 | How many pixels to ignore during resize check if virtual-scroller (or parentScroll) are only resized by a very small amount. |
scrollAnimationTime | number 750 | The time in milliseconds for the scroll animation to run for. 0 will completely disable the tween/animation. |
scrollDebounceTime | number 0 | Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons). |
scrollInto | Function | (item:any, alignToBeginning:boolean = true, additionalOffset:number = 0, animationMilliseconds:number = undefined, animationCompletedCallback:()=>void = undefined)=>void - Scrolls to item |
scrollThrottlingTime | number 0 | Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons). |
scrollToIndex | Function | (index:number, alignToBeginning:boolean = true, additionalOffset:number = 0, animationMilliseconds:number = undefined, animationCompletedCallback:()=>void = undefined)=>void - Scrolls to item at index |
scrollToPosition | Function | (scrollPosition:number, animationMilliseconds:number = undefined, animationCompletedCallback: ()=>void = undefined)=>void - Scrolls to px position |
scrollbarHeight | number | If you want to override the auto-calculated scrollbar height. This is used to determine the dimensions of the viewable area when calculating the number of items to render. |
scrollbarWidth | number | If you want to override the auto-calculated scrollbar width. This is used to determine the dimensions of the viewable area when calculating the number of items to render. |
ssrChildHeight | number | The hard-coded height of the item template's cell to use if rendering via Angular Universal/Server-Side-Rendering |
ssrChildWidth | number | The hard-coded width of the item template's cell to use if rendering via Angular Universal/Server-Side-Rendering |
ssrViewportHeight | number 1080 | The hard-coded visible height of the virtual-scroller (or [parentScroll]) to use if rendering via Angular Universal/Server-Side-Rendering. |
ssrViewportWidth | number 1920 | The hard-coded visible width of the virtual-scroller (or [parentScroll]) to use if rendering via Angular Universal/Server-Side-Rendering. |
stripedTable | boolean false | Set to true if you use a striped table. In this case, the rows will be added/removed two by two to keep the strips consistent. |
useMarginInsteadOfTranslate | boolean false | Translate is faster in many scenarios because it can use GPU acceleration, but it can be slower if your scroll container or child elements don't use any transitions or opacity. More importantly, translate creates a new "containing block" which breaks position:fixed because it'll be relative to the transform rather than the window. If you're experiencing issues with position:fixed on your child elements, turn this flag on. |
viewPortInfo | IPageInfo | Allows querying the the current viewport info on demand rather than listening for events. |
viewPortItems | any[] | The array of items currently being rendered to the viewport. |
vsChange | Event<IPageInfo> | This event is fired every time the start or end indexes or scroll position change and emits IPageInfo . |
vsEnd | Event<IPageInfo> | This event is fired every time end index changes and emits IPageInfo . |
vsStart | Event<IPageInfo> | This event is fired every time start index changes and emits IPageInfo . |
vsUpdate | Event<any[]> | This event is fired every time the start or end indexes change and emits the list of items which should be visible based on the current scroll position from start to end . The list emitted by this event must be used with *ngFor to render the actual list of items within <virtual-scroller> |
childHeight (DEPRECATED) | number | The minimum height of the item template's cell. Use this if enableUnequalChildrenSizes isn't working well enough. (The actual rendered size of the first cell is used by default if not specified.) |
childWidth (DEPRECATED) | number | The minimum width of the item template's cell. Use this if enableUnequalChildrenSizes isn't working well enough. (The actual rendered size of the first cell is used by default if not specified.) |
Note - The Events without the "vs" prefix have been deprecated because they might conflict with native DOM events due to their "bubbling" nature. See https://github.com/angular/angular/issues/13997
An example is if an <input>
element inside <virtual-scroller>
emits a "change" event which bubbles up to the (change) handler of virtual-scroller. Using the vs prefix will prevent this bubbling conflict because there are currently no official DOM events prefixed with vs.
If you want to use the scrollbar of a parent element, set parentScroll
to a native DOM element.
1<div #scrollingBlock> 2 <virtual-scroller #scroll [items]="items" [parentScroll]="scrollingBlock"> 3 <input type="search"> 4 <div #container> 5 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 6 </my-custom-component> 7 </div> 8 </virtual-scroller> 9</div>
If the parentScroll is a custom angular component (instead of a native HTML element such as DIV), Angular will wrap the #scrollingBlock
variable in an ElementRef https://angular.io/api/core/ElementRef in which case you'll need to use the .nativeElement
property to get to the underlying JavaScript DOM element reference.
1<custom-angular-component #scrollingBlock> 2 <virtual-scroller #scroll [items]="items" [parentScroll]="scrollingBlock.nativeElement"> 3 <input type="search"> 4 <div #container> 5 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 6 </my-custom-component> 7 </div> 8 </virtual-scroller> 9</custom-angular-component>
Note - The parent element should have a width and height defined.
If you want to use the window's scrollbar, set parentScroll
.
1<virtual-scroller #scroll [items]="items" [parentScroll]="scroll.window"> 2 <input type="search"> 3 <div #container> 4 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 5 </my-custom-component> 6 </div> 7</virtual-scroller>
Items must have fixed height and width for this module to work perfectly. If not, set [enableUnequalChildrenSizes]="true"
.
(DEPRECATED): If enableUnequalChildrenSizes
isn't working, you can set inputs childWidth
and childHeight
to their smallest possible values. You can also modify bufferAmount
which causes extra items to be rendered on the edges of the scrolling area.
1<virtual-scroller #scroll [items]="items" [enableUnequalChildrenSizes]="true"> 2 3 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 4 </my-custom-component> 5 6</virtual-scroller>
The event vsEnd
is fired every time the scrollbar reaches the end of the list. You could use this to dynamically load more items at the end of the scroll. See below.
1import { IPageInfo } from 'ngx-virtual-scroller'; 2... 3 4@Component({ 5 selector: 'list-with-api', 6 template: ` 7 <virtual-scroller #scroll [items]="buffer" (vsEnd)="fetchMore($event)"> 8 <my-custom-component *ngFor="let item of scroll.viewPortItems"> </my-custom-component> 9 <div *ngIf="loading" class="loader">Loading...</div> 10 </virtual-scroller> 11 ` 12}) 13export class ListWithApiComponent implements OnChanges { 14 15 @Input() 16 items: ListItem[]; 17 18 protected buffer: ListItem[] = []; 19 protected loading: boolean; 20 21 protected fetchMore(event: IPageInfo) { 22 if (event.endIndex !== this.buffer.length-1) return; 23 this.loading = true; 24 this.fetchNextChunk(this.buffer.length, 10).then(chunk => { 25 this.buffer = this.buffer.concat(chunk); 26 this.loading = false; 27 }, () => this.loading = false); 28 } 29 30 protected fetchNextChunk(skip: number, limit: number): Promise<ListItem[]> { 31 return new Promise((resolve, reject) => { 32 .... 33 }); 34 } 35}
Note - The #header
angular selector will make the <thead>
element fixed to top. If you want the header to scroll out of view don't add the #header
angular element ref.
1<virtual-scroller #scroll [items]="myItems"> 2 <table> 3 <thead #header> 4 <th>Index</th> 5 <th>Name</th> 6 <th>Gender</th> 7 <th>Age</th> 8 <th>Address</th> 9 </thead> 10 <tbody #container> 11 <tr *ngFor="let item of scroll.viewPortItems"> 12 <td>{{item.index}}</td> 13 <td>{{item.name}}</td> 14 <td>{{item.gender}}</td> 15 <td>{{item.age}}</td> 16 <td>{{item.address}}</td> 17 </tr> 18 </tbody> 19 </table> 20</virtual-scroller>
virtual-scroller caches the measurements for the rendered items. If enableUnequalChildrenSizes===true
then each item is measured and cached separately. Otherwise, the 1st measured item is used for all items.
If your items can change sizes dynamically, you'll need to notify virtual-scroller to re-measure them. There are 3 methods for doing this:
1virtualScroller.invalidateAllCachedMeasurements(); 2virtualScroller.invalidateCachedMeasurementForItem(item: any); 3virtualScroller.invalidateCachedMeasurementAtIndex(index: number);
virtual-scroller essentially uses *ngIf
to remove items that are scrolled out of view. This is what gives the performance benefits compared to keeping all the off-screen items in the DOM.
Because of the *ngIf, Angular completely forgets any view state. If your component has the ability to change state, it's your app's responsibility to retain that viewstate in your own object which data-binds to the component.
For example, if your child component can expand/collapse via a button, most likely scrolling away & back will cause the expansion state to revert to the default state.
To fix this, you'll need to store any "view" state properties in a variable & data-bind to it so that it can be restored when it gets removed/re-added from the DOM.
Example:
1<virtual-scroller #scroll [items]="items"> 2 <my-custom-component [expanded]="item.expanded" *ngFor="let item of scroll.viewPortItems"> 3 </my-custom-component> 4</virtual-scroller>
Note - This should now be auto-detected, however the 'refresh' method can still force it if neeeded.
This was implemented using the setInterval
method which may cause minor performance issues. It shouldn't be noticeable, but can be disabled via [checkResizeInterval]="0"
Performance will be improved once "Resize Observer" (https://wicg.github.io/ResizeObserver/) is fully implemented.
Refresh method (DEPRECATED)
If virtual scroll is used within a dropdown or collapsible menu, virtual scroll needs to know when the container size changes. Use refresh()
function after container is resized (include time for animation as well).
1import { Component, ViewChild } from '@angular/core';
2import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
3
4@Component({
5 selector: 'rj-list',
6 template: `
7 <virtual-scroller #scroll [items]="items">
8 <div *ngFor="let item of scroll.viewPortItems; let i = index">
9 {{i}}: {{item}}
10 </div>
11 </virtual-scroller>
12 `
13})
14export class ListComponent {
15
16 protected items = ['Item1', 'Item2', 'Item3'];
17
18 @ViewChild(VirtualScrollerComponent)
19 private virtualScroller: VirtualScrollerComponent;
20
21 // call this function after resize + animation end
22 afterResize() {
23 this.virtualScroller.refresh();
24 }
25}
You can use the scrollInto()
or scrollToIndex()
API to scroll into an item in the list:
1import { Component, ViewChild } from '@angular/core';
2import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
3
4@Component({
5 selector: 'rj-list',
6 template: `
7 <virtual-scroller #scroll [items]="items">
8 <div *ngFor="let item of scroll.viewPortItems; let i = index">
9 {{i}}: {{item}}
10 </div>
11 </virtual-scroller>
12 `
13})
14export class ListComponent {
15
16 protected items = ['Item1', 'Item2', 'Item3'];
17
18 @ViewChild(VirtualScrollerComponent)
19 private virtualScroller: VirtualScrollerComponent;
20
21 // call this function whenever you have to focus on second item
22 focusOnAnItem() {
23 this.virtualScroller.items = this.items;
24 this.virtualScroller.scrollInto(items[1]);
25 }
26}
Some default config settings can be overridden via DI, so you can set them globally instead of on each instance of virtual-scroller.
1providers: [ 2 provide: 'virtual-scroller-default-options', useValue: { 3 checkResizeInterval: 1000, 4 modifyOverflowStyleOfParentScroll: true, 5 resizeBypassRefreshThreshold: 5, 6 scrollAnimationTime: 750, 7 scrollDebounceTime: 0, 8 scrollThrottlingTime: 0, 9 stripedTable: false 10 } 11],
OR
1export function vsDefaultOptionsFactory(): VirtualScrollerDefaultOptions { 2 return { 3 checkResizeInterval: 1000, 4 modifyOverflowStyleOfParentScroll: true, 5 resizeBypassRefreshThreshold: 5, 6 scrollAnimationTime: 750, 7 scrollDebounceTime: 0, 8 scrollThrottlingTime: 0, 9 stripedTable: false 10 }; 11} 12 13providers: [ 14 provide: 'virtual-scroller-default-options', useFactory: vsDefaultOptionsFactory 15],
Always be sure to send an immutable copy of items to virtual scroll to avoid unintended behavior. You need to be careful when doing non-immutable operations such as sorting:
1sort() { 2 this.items = [].concat(this.items || []).sort() 3}
This hacky CSS allows hiding a scrollbar while still enabling scroll through mouseWheel/touch/pageUpDownKeys
1 // hide vertical scrollbar 2 margin-right: -25px; 3 padding-right: 25px; 4 5 // hide horizontal scrollbar 6 margin-bottom: -25px; 7 padding-bottom: 25px;
If you want to nest additional elements inside virtual scroll besides the list itself (e.g. search field), you need to wrap those elements in a tag with an angular selector name of #container
.
1<virtual-scroller #scroll [items]="items"> 2 <input type="search"> 3 <div #container> 4 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 5 </my-custom-component> 6 </div> 7</virtual-scroller>
virtual-scroller uses *ngFor
to render the visible items. When an *ngFor
array changes, Angular uses a trackBy function to determine if it should re-use or re-generate each component in the loop.
For example, if 5 items are visible and scrolling causes 1 item to swap out but the other 4 remain visible, there's no reason Angular should re-generate those 4 components from scratch, it should reuse them.
A trackBy function must return either a number or string as a unique identifier for your object.
If the array used by *ngFor
is of type number[]
or string[]
, Angular's default trackBy function will work automatically, you don't need to do anything extra.
If the array used by *ngFor
is of type any[]
, you must code your own trackBy function.
Here's an example of how to do this:
1<virtual-scroller #scroll [items]="myComplexItems"> 2 <my-custom-component 3 [myComplexItem]="complexItem" 4 *ngFor="let complexItem of scroll.viewPortItems; trackBy: myTrackByFunction"> 5 </my-custom-component> 6</virtual-scroller>
1public interface IComplexItem { 2 uniqueIdentifier: number; 3 extraData: any; 4} 5 6public myTrackByFunction(index: number, complexItem: IComplexItem): number { 7 return complexItem.uniqueIdentifier; 8}
virtual-scroller is coded to be extremely fast. If scrolling is slow in your app, the issue is with your custom component code, not with virtual-scroller itself. Below is an explanation of how to correct your code. This will make your entire app much faster, including virtual-scroller.
Each component in Angular by default uses the ChangeDetectionStrategy.Default
"CheckAlways" strategy. This means that Change Detection cycles will be running constantly which will check EVERY data-binding expression on EVERY component to see if anything has changed.
This makes it easier for programmers to code apps, but also makes apps extremely slow.
If virtual-scroller feels slow, a possible quick solution that masks the real problem is to use scrollThrottlingTime
or scrollDebounceTime
APIs.
The correct fix is to make cycles as fast as possible and to avoid unnecessary ChangeDetection cycles. Cycles will be faster if you avoid complex logic in data-bindings. You can avoid unnecessary Cycles by converting your components to use ChangeDetectionStrategy.OnPush
.
ChangeDetectionStrategy.OnPush means the consuming app is taking full responsibility for telling Angular when to run change detection rather than allowing Angular to figure it out itself. For example, virtual-scroller has a bound property [items]="myItems"
. If you use OnPush, you have to tell Angular when you change the myItems array, because it won't determine this automatically.
OnPush is much harder for the programmer to code. You have to code things differently: This means
If your biggest priority is making virtual-scroller faster, the best candidates for OnPush will be all custom components being used as children underneath virtual-scroller. If you have a hierarchy of multiple custom components under virtual-scroller, ALL of them need to be converted to OnPush.
My personal suggestion on the easiest way to implement OnPush across your entire app:
1import { ChangeDetectorRef } from '@angular/core'; 2 3public class ManualChangeDetection { 4 public queueChangeDetection(): void { 5 this.changeDetectorRef.markForCheck(); // marks self for change detection on the next cycle, but doesn't actually schedule a cycle 6 this.queueApplicationTick(); 7 } 8 9 public static STATIC_APPLICATION_REF: ApplicationRef; 10 public static queueApplicationTick: ()=> void = Util.debounce(() => { 11 if (ManualChangeDetection.STATIC_APPLICATION_REF['_runningTick']) { 12 return; 13 } 14 15 ManualChangeDetection.STATIC_APPLICATION_REF.tick(); 16 }, 5); 17 18 constructor(private changeDetectorRef: ChangeDetectorRef) { 19 } 20} 21 22// note: this portion is only needed if you don't already have a debounce implementation in your app 23public class Util { 24 public static throttleTrailing(func: Function, wait: number): Function { 25 let timeout = undefined; 26 let _arguments = undefined; 27 const result = function () { 28 const _this = this; 29 _arguments = arguments; 30 31 if (timeout) { 32 return; 33 } 34 35 if (wait <= 0) { 36 func.apply(_this, _arguments); 37 } else { 38 timeout = setTimeout(function () { 39 timeout = undefined; 40 func.apply(_this, _arguments); 41 }, wait); 42 } 43 }; 44 result['cancel'] = function () { 45 if (timeout) { 46 clearTimeout(timeout); 47 timeout = undefined; 48 } 49 }; 50 51 return result; 52 } 53 54 public static debounce(func: Function, wait: number): Function { 55 const throttled = Util.throttleTrailing(func, wait); 56 const result = function () { 57 throttled['cancel'](); 58 throttled.apply(this, arguments); 59 }; 60 result['cancel'] = function () { 61 throttled['cancel'](); 62 }; 63 64 return result; 65 } 66} 67 68public class MyEntryLevelAppComponent 69{ 70 constructor(applicationRef: ApplicationRef) { 71 ManualChangeDetection.STATIC_APPLICATION_REF = applicationRef; 72 } 73} 74 75@Component({ 76 ... 77 changeDetection: ChangeDetectionStrategy.OnPush 78 ... 79}) 80public class SomeRandomComponentWhichUsesOnPush { 81 private manualChangeDetection: ManualChangeDetection; 82 constructor(changeDetectorRef: ChangeDetectorRef) { 83 this.manualChangeDetection = new ManualChangeDetection(changeDetectorRef); 84 } 85 86 public someFunctionThatMutatesState(): void { 87 this.someBoundProperty = someNewValue; 88 89 this.manualChangeDetection.queueChangeDetection(); 90 } 91}
The ManualChangeDetection/Util classes are helpers that can be copy/pasted directly into your app. The code for MyEntryLevelAppComponent & SomeRandomComponentWhichUsesOnPush are examples that you'll need to modify for your specific app. If you follow this pattern, OnPush is much easier to implement. However, the really hard part is analyzing all of your code to determine where you're mutating state. Unfortunately there's no magic bullet for this, you'll need to spend a lot of time reading/debugging/testing your code.
This API is meant as a quick band-aid fix for performance issues. Please read the other performance sections above to learn the ideal way to fix performance issues.
ChangeDetectionStrategy.OnPush
is the recommended strategy as it improves the entire app performance, not just virtual-scroller. However, ChangeDetectionStrategy.OnPush
is hard to implement. executeRefreshOutsideAngularZone
may be an easier initial approach until you're ready to tackle ChangeDetectionStrategy.OnPush
.
If you've correctly implemented ChangeDetectionStrategy.OnPush
for 100% of your components, the executeRefreshOutsideAngularZone
will not provide any performance benefit.
If you have not yet done this, scrolling may feel slow. This is because Angular performs a full-app change detection while scrolling. However, it's likely that only the components inside the scroller actually need the change detection to run, so a full-app change detection cycle is overkill.
In this case you can get a free/easy performance boost with the following code:
1import { ChangeDetectorRef } from '@angular/core'; 2 3public class MainComponent { 4 constructor(public changeDetectorRef: ChangeDetectorRef) { } 5}
1<virtual-scroller 2 #scroll 3 [items]="items" 4 [executeRefreshOutsideAngularZone]="true" 5 (vsUpdate)="changeDetectorRef.detectChanges()" 6> 7 <my-custom-component *ngFor="let item of scroll.viewPortItems"> 8 </my-custom-component> 9</virtual-scroller>
Note - executeRefreshOutsideAngularZone
will disable Angular ChangeDetection during all virtual-scroller events, including: vsUpdate, vsStart, vsEnd, vsChange. If you change any data-bound properties inside these event handlers, you must perform manual change detection on those specific components. This can be done via changeDetectorRef.detectChanges()
at the end of the event handler.
Note - The changeDetectorRef
is component-specific, so you'll need to inject it into a private variable in the constructor of the appropriate component before calling it in response to the virtual-scroller events.
:warning: WARNING - Failure to perform manual change detection in response to virtual-scroller events will cause your components to render a stale UI for a short time (until the next Change Detection cycle), which will make your app feel buggy.
Note - changeDetectorRef.detectChanges()
will execute change detection on the component and all its nested children. If multiple components need to run change detection in response to a virtual-scroller event, you can call detectChanges from a higher-level component in the ancestor hierarchy rather than on each individual component. However, its important to avoid too many extra change detection cycles by not going too high in the hierarchy unless all the nested children really need to have change detection performed.
Note - All virtual-scroller events are emitted at the same time in response to its internal "refresh" function. Some of these event emitters are bypassed if certain criteria don't apply. however vsUpdate will always be emitted. For this reason, you should consolidate all data-bound property changes & manual change detection into the vsUpdate event handler, to avoid duplicate change detection cycles from executing during the other virtual-scroller events.
In the above code example, (vsUpdate)="changeDetectorRef.detectChanges()"
is necessary because scroll.viewPortItems
was changed internally be virtual-scroller during its internal "render" function before emitting (vsUpdate). executeRefreshOutsideAngularZone
prevents MainComponent from refreshing its data-binding in response to this change, so a manual Change Detection cycle must be run. No extra manual change detection code is necessary for virtual-scroller or my-custom-component, even if their data-bound properties have changed, because they're nested children of MainComponent.
These APIs are meant as a quick band-aid fix for performance issues. Please read the other performance sections above to learn the ideal way to fix performance issues.
Without these set, virtual-scroller will refresh immediately whenever the user scrolls. Throttle will delay refreshing until # milliseconds after scroll started. As the user continues to scroll, it will wait the same # milliseconds in between each successive refresh. Even if the user stops scrolling, it will still wait the allocated time before the final refresh. Debounce won't refresh until the user has stopped scrolling for # milliseconds. If both Debounce & Throttling are set, debounce takes precedence.
Note - If virtual-scroller hasn't refreshed & the user has scrolled past bufferAmount, no child items will be rendered and virtual-scroller will appear blank. This may feel confusing to the user. You may want to have a spinner or loading message display when this occurs.
The initial SSR render isn't a fully functioning site, it's essentially an HTML "screenshot" (HTML/CSS, but no JS). However, it immediately swaps out your "screenshot" with the real site as soon as the full app has downloaded in the background. The intent of SSR is to give a correct visual very quickly, because a full angular app could take a long time to download. This makes the user think your site is fast, because hopefully they won't click on anything that requires JS before the fully-functioning site has finished loading in the background. Also, it allows screen scrapers without JavaScript to work correctly (example: Facebook posts/etc).
virtual-scroller relies on JavaScript APIs to measure the size of child elements and the scrollable area of their parent. These APIs do not work in SSR because the HTML/CSS "screenshot" is generated on the server via Node, it doesn't execute/render the site as a browser would. This means virtual-scroller will see all measurements as undefined and the "screenshot" will not be generated correctly. Most likely, only 1 child element will appear in your virtual-scroller. This "screenshot" can be fixed with polyfills. However, when the browser renders the "screenshot", the scrolling behaviour still won't work until the full app has loaded.
SSR is an advanced (and complex) topic that can't be fully addressed here. Please research this on your own. However, here are some suggestions:
main.server.ts
file1const domino = require('domino'); 2require('raf/polyfill'); 3const win = domino.createWindow(template); 4win['versionNumber'] = 'development'; 5global['window'] = win; 6global['document'] = win.document; 7Object.defineProperty(win.document.body.style, 'transform', { value: () => { return { enumerable: true, configurable: true }; } });
[parentScroll]
element). Use these values to set the [ssrChildWidth]
/[ssrChildHeight]
/[ssrViewportWidth]
/[ssrViewportHeight]
properties.1<virtual-scroller #scroll [items]="items"> 2 3 <my-custom-component 4 *ngFor="let item of scroll.viewPortItems" 5 [ssrChildWidth]="138" 6 [ssrChildHeight]="175" 7 [ssrViewportWidth]="1500" 8 [ssrViewportHeight]="800" 9 > 10 </my-custom-component> 11 12</virtual-scroller>
The following are known issues that we don't know how to solve or don't have the resources to do so. Please don't submit a ticket for them. If you have an idea on how to fix them, please submit a pull request :slightly_smiling_face:
If there are 2 nested scrollbars on the page the mouse scrollwheel will only affect the scrollbar of the nearest parent to the current mouse position. This means if you scroll to the bottom of a virtual-scroller using the mousewheel & the window has an extra scrollbar, you cannot use the scrollwheel to scroll the page unless you move the mouse pointer out of the virtual-scroller element.
Contributions are very welcome! Just send a pull request. Feel free to contact me or checkout my GitHub page.
Follow me: GitHub | Facebook | Twitter | Google+ | Youtube
The MIT License (MIT)
Copyright (c) 2016 Rinto Jose (rintoj)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
No vulnerabilities found.
No security vulnerabilities found.