Virtual Scroll displays a virtual, "infinite" list. Supports horizontal/vertical, variable heights, & multi-column.
ngx-virtual-scroller. Please update your package.json
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.
- Supports multi-column
- Easy to use APIs
- Open source and available in GitHub
v3.0.0Several deprecated properties removed (see changelog).
- If items array is prepended with additional items, keep scroll on currently visible items, if possible. There is no flag to disable this, because it seems to be the best user-experience in all cases. If you disagree, please create an issue.
v2.1.0Dependency Injection syntax was changed.
v1.0.6viewPortIndices API property removed. (use viewPortInfo instead)
v1.0.3Renamed everything from virtual-scroll to virtual-scroller and from virtualScroll to virtualScroller
v0.4.13resizeBypassRefreshTheshold renamed to resizeBypassRefreshThreshold (typo)
v0.4.12The start and end values of the change/start/end events were including bufferAmount, which made them confusing. This has been corrected.
- viewPortIndices.arrayStartIndex renamed to viewPortIndices.startIndex and viewPortIndices.arrayEndIndex renamed to viewPortIndices.endIndex
v0.4.4The 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.
- RTL Support on Horizontal scrollers
- Support for fixed
- Added API to query for current scroll px position (also passed as argument to
- Added API to invalidate cached child item measurements (if your child item sizes change dynamically)
- Added API to scroll to specific px position
- If scroll container resizes, the items will auto-refresh. Can be disabled if it causes any performance issues by setting
useMarginInsteadOfTranslateflag. 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.
- Support for horizontal scrollbars
- Support for elements with different sizes
- Added ability to put other elements inside of scroll (Need to wrap list itself in @ContentChild('container'))
- Added ability to use any parent with scrollbar instead of this element (@Input() parentScroll)
option 2: note: viewPortItems must be a public field to work with AOT
option 3: note: viewPortItems must be a public field to work with AOT
Step 1: Install ngx-virtual-scroller
npm install ngx-virtual-scroller
Step 2: Import virtual scroll module into your app module
Step 3: Wrap virtual-scroller tag around elements;
virtual-scroller #scroll ="items"my-custom-component *ngFor="let item of scroll.viewPortItems"/my-custom-component/virtual-scroller
You must also define width and height for the container and for its children.
Step 4: Create
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.
In alphabetical order:
||The number of elements to be rendered above & below the current container's viewport. Increase this if
||How often in milliseconds to check if virtual-scroller (or parentScroll) has been resized. If resized, it'll call
||Predicate of syntax
||If you want to use the "unequal size" children feature. This is not perfect, but hopefully "close-enough" for most situations.|
||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.|
||Whether the scrollbars should be vertical or horizontal.|
|items||any||The data that builds the templates within the virtual scroll. This is the same data that you'd pass to
||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|
||How many pixels to ignore during resize check if virtual-scroller (or parentScroll) are only resized by a very small amount.|
||The time in milliseconds for the scroll animation to run for. 0 will completely disable the tween/animation.|
||Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons).|
||Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons).|
||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.|
||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.|
||The hard-coded height of the item template's cell to use if rendering via Angular Universal/Server-Side-Rendering|
||The hard-coded width of the item template's cell to use if rendering via Angular Universal/Server-Side-Rendering|
||The hard-coded visible height of the virtual-scroller (or [parentScroll]) to use if rendering via Angular Universal/Server-Side-Rendering.|
||The hard-coded visible width of the virtual-scroller (or [parentScroll]) to use if rendering via Angular Universal/Server-Side-Rendering.|
||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.|
||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.|
||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.|
||This event is fired every time the
||This event is fired every time
||This event is fired every time
||This event is fired every time the
||The minimum height of the item template's cell. Use this if
||The minimum width of the item template's cell. Use this if
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.
Use parent scrollbar
If you want to use the scrollbar of a parent element, set
parentScroll to a native DOM element.
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
Note - The parent element should have a width and height defined.
Use scrollbar of window
If you want to use the window's scrollbar, set
Items with variable size
Items must have fixed height and width for this module to work perfectly. If not, set
enableUnequalChildrenSizes isn't working, you can set inputs
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.
Loading in chunks
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.
With HTML Table
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.
If child size changes
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:
virtualScroller.invalidateAllCachedMeasurements;virtualScroller.invalidateCachedMeasurementForItemitem: any;virtualScroller.invalidateCachedMeasurementAtIndexindex: number;
If child view state is reverted after scrolling away & back
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.
If container size changes
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
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).
Focus an item
You can use the
scrollToIndex() API to scroll into an item in the list:
Dependency Injection of configuration settings
Some default config settings can be overridden via DI, so you can set them globally instead of on each instance of virtual-scroller.
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:
This hacky CSS allows hiding a scrollbar while still enabling scroll through mouseWheel/touch/pageUpDownKeys
// hide vertical scrollbarmargin-right: -25px;padding-right: 25px;// hide horizontal scrollbarmargin-bottom: -25px;padding-bottom: 25px;
Additional elements in scroll
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
Performance - TrackBy
*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
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:
publicpublic myTrackByFunctionindex: number, complexItem: IComplexItem: number
Performance - ChangeDetection
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
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 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
- avoid mutating state on any bound properties where possible &
- manually running change detection when you do mutate state. OnPush can be done on a component-by-component basis, however I recommend doing it for EVERY component in your app.
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:
;public// note: this portion is only needed if you don't already have a debounce implementation in your apppublicpublicpublic
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.
Performance - executeRefreshOutsideAngularZone
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
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:
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 - 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.
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.
Performance - scrollDebounceTime / scrollThrottlingTime
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.
Angular Universal / Server-Side Rendering
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:
- Use https://www.npmjs.com/package/domino and https://www.npmjs.com/package/raf polyfills in your
;require'raf/polyfill';;win = 'development';global = win;global = win.document;Object.definePropertywin.document.body.style, 'transform', ;
- Determine a default screen size you want to use for the SSR "screenshot" calculations (suggestion: 1920x1080). This won't be accurate for all users, but will hopefully be close enough. Once the full Angular app loads in the background, their real device screensize will take over.
- Run your app in a real browser without SSR and determine the average width/height of the child elements inside virtual-scroller as well as the width/height of the virtual-scroller (or
[parentScroll]element). Use these values to set the
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 🙂
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.
- Rinto Jose (rintoj)
- Devin Garner (speige)
- Pavel Kukushkin (kykint)
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.