![Introducing Enhanced Alert Actions and Triage Functionality](https://cdn.sanity.io/images/cgdhsj6q/production/fe71306d515f85de6139b46745ea7180362324f0-2530x946.png?w=800&fit=max&auto=format)
Product
Introducing Enhanced Alert Actions and Triage Functionality
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
ngx-virtual-scroller
Advanced tools
Changelog
v1.0.6
Readme
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.
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.
<virtual-scroller #scroll [items]="items">
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</virtual-scroller>
alternatively
<virtual-scroller [items]="items" (vsUpdate)="viewPortItems = $event">
<my-custom-component *ngFor="let item of viewPortItems">
</my-custom-component>
</virtual-scroller>
alternatively
<div virtualScroller [items]="items" (vsUpdate)="viewPortItems = $event">
<my-custom-component *ngFor="let item of viewPortItems">
</my-custom-component>
</div>
Step 1: Install ngx-virtual-scroller
npm install ngx-virtual-scroller --save
Step 2: Import virtual scroll module into your app module
....
import { VirtualScrollerModule } from 'ngx-virtual-scroller';
....
@NgModule({
...
imports: [
....
VirtualScrollerModule
],
....
})
export class AppModule { }
Step 3: Wrap virtual-scroller tag around elements;
<virtual-scroller #scroll [items]="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.
virtual-scroller {
display: block;
width: 350px;
height: 200px;
}
my-custom-component {
display: block;
width: 100%;
height: 30px;
}
Step 4: Create 'my-custom-component' component.
'my-custom-component' must be a custom angular2 component, outside of this library.
Child component is not necessary if your item is simple enough. See below.
<virtual-scroller #scroll [items]="items">
<div *ngFor="let item of scroll.viewPortItems">{{item?.name}}</div>
</virtual-scroller>
interface IPageInfo {
startIndex: number;
endIndex: number;
scrollStartPosition: number;
scrollEndPosition: number;
startIndexWithBuffer: number;
endIndexWithBuffer: number;
maxScrollPosition: number;
}
interface ChangeEvent extends IPageInfo {
start: number; (DEPRECATED)
end: number; (DEPRECATED)
}
Attribute | Type | Description |
---|---|---|
checkResizeInterval | number | How often in milliseconds to check if virtual-scroller (or parentScroll) has been resized. If resized, it'll call Refresh() method. Defaults to 1000. Can be injected by DI with token "virtualScroller.checkResizeInterval". |
resizeBypassRefreshThreshold | number | How many pixels to ignore during resize check if virtual-scroller (or parentScroll) are only resized by a very small amount. Defaults to 5. Can be injected by DI with token "virtualScroller.resizeBypassRefreshThreshold". |
enableUnequalChildrenSizes | boolean | If you want to use the "unequal size" children feature. This is not perfect, but hopefully "close-enough" for most situations. Defaults to false. |
scrollDebounceTime | number | Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons). Default is 0. Can be injected by DI with token "virtualScroller.scrollDebounceTime". |
scrollThrottlingTime | number | Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons). Default is 0. Can be injected by DI with token "virtualScroller.scrollThrottlingTime". |
useMarginInsteadOfTranslate | boolean | Defaults to 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. |
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. Can be injected by DI with token "virtualScroller.scrollbarWidth". |
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. Can be injected by DI with token "virtualScroller.scrollbarHeight". |
horizontal | boolean | Whether the scrollbars should be vertical or horizontal. Defaults to false. |
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. |
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.) |
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.) |
bufferAmount | number | The number of elements to be rendered above & below the current container's viewport. Increase this if enableUnequalChildrenSizes isn't working well enough. (defaults to enableUnequalChildrenSizes ? 5 : 0) |
scrollAnimationTime | number | The time in milliseconds for the scroll animation to run for. Default value is 750. 0 will completely disable the tween/animation. Can be injected by DI with token "virtualScroller.scrollAnimationTime". |
parentScroll | Element / Window | Element (or window), which will have scrollbar. This element must be one of the parents of virtual-scroller |
compareItems | Function | 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). Defaults to === comparison. |
start (DEPRECATED) / vsStart | Event | This event is fired every time start index changes and emits ChangeEvent . |
end (DEPRECATED) / vsEnd | Event | This event is fired every time end index changes and emits ChangeEvent . |
change (DEPRECATED) / vsChange | Event | This event is fired every time the start or end indexes or scroll position change and emits ChangeEvent . |
update (DEPRECATED) / 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> |
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. |
refresh (DEPRECATED) | ()=>void | Function to force re-rendering of current items in viewport. |
invalidateAllCachedMeasurements | ()=>void | Function to force re-measuring all cached item sizes. If enableUnequalChildrenSizes===false, only 1 item will be re-measured. |
invalidateCachedMeasurementForItem | (item:any)=>void | Function to force re-measuring cached item size. |
invalidateCachedMeasurementAtIndex | (index:number)=>void | Function to force re-measuring cached item size. |
scrollInto | (item:any, alignToBeginning:boolean = true, additionalOffset:number = 0, animationMilliseconds:number = undefined, animationCompletedCallback:()=>void = undefined)=>void | Scrolls to item |
scrollToIndex | (index:number, alignToBeginning:boolean = true, additionalOffset:number = 0, animationMilliseconds:number = undefined, animationCompletedCallback:()=>void = undefined)=>void | Scrolls to item at index |
scrollToPosition | (scrollPosition:number, animationMilliseconds:number = undefined, animationCompletedCallback: ()=>void = undefined)=>void | Scrolls to px position |
ssrChildWidth | number | The hard-coded width of the item template's cell to use if rendering via Angular Universal/Server-Side-Rendering |
ssrChildHeight | number | The hard-coded height of the item template's cell to use if rendering via Angular Universal/Server-Side-Rendering |
ssrViewportWidth | number | The hard-coded visible width of the virtual-scroller (or [parentScroll]) to use if rendering via Angular Universal/Server-Side-Rendering. Defaults to 1920. |
ssrViewportHeight | number | The hard-coded visible height of the virtual-scroller (or [parentScroll]) to use if rendering via Angular Universal/Server-Side-Rendering. Defaults to 1080. |
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 element inside 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 are using AOT compilation (I hope you are) then with classic usage (listening to update
event) you are required to create a public field viewPortItems
in your component.
Here's a way to avoid it:
<virtual-scroller #scroll [items]="items">
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</virtual-scroller>
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.
<virtual-scroller #scroll [items]="items">
<input type="search">
<div #container>
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</div>
</virtual-scroller>
If you want to use the scrollbar of a parent element, set parentScroll
to a native DOM element.
<div #scrollingBlock>
<virtual-scroller #scroll [items]="items" [parentScroll]="scrollingBlock">
<input type="search">
<div #container>
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</div>
</virtual-scroller>
</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.
<custom-angular-component #scrollingBlock>
<virtual-scroller #scroll [items]="items" [parentScroll]="scrollingBlock.nativeElement">
<input type="search">
<div #container>
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</div>
</virtual-scroller>
</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
.
<virtual-scroller #scroll [items]="items" [parentScroll]="scroll.window">
<input type="search">
<div #container>
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</div>
</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.
<virtual-scroller #scroll [items]="items" [enableUnequalChildrenSizes]="true">
<my-custom-component *ngFor="let item of scroll.viewPortItems">
</my-custom-component>
</virtual-scroller>
The event end
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.
import { ChangeEvent } from 'ngx-virtual-scroller';
...
@Component({
selector: 'list-with-api',
template: `
<virtual-scroller [items]="buffer" (vsUpdate)="scrollItems = $event"
(vsEnd)="fetchMore($event)">
<my-custom-component *ngFor="let item of scrollItems"> </my-custom-component>
<div *ngIf="loading" class="loader">Loading...</div>
</virtual-scroller>
`
})
export class ListWithApiComponent implements OnChanges {
@Input()
items: ListItem[];
protected buffer: ListItem[] = [];
protected loading: boolean;
protected fetchMore(event: ChangeEvent) {
if (event.end !== this.buffer.length-1) return;
this.loading = true;
this.fetchNextChunk(this.buffer.length, 10).then(chunk => {
this.buffer = this.buffer.concat(chunk);
this.loading = false;
}, () => this.loading = false);
}
protected fetchNextChunk(skip: number, limit: number): Promise<ListItem[]> {
return new Promise((resolve, reject) => {
....
});
}
}
Note: The #header angular selector will make the element fixed to top. If you want the header to scroll out of view don't add the #header angular element ref.
<virtual-scroller #scroll [items]="myItems">
<table>
<thead #header>
<th>Index</th>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Address</th>
</thead>
<tbody #container>
<tr *ngFor="let item of scroll.viewPortItems">
<td>{{item.index}}</td>
<td>{{item.name}}</td>
<td>{{item.gender}}</td>
<td>{{item.age}}</td>
<td>{{item.address}}</td>
</tr>
</tbody>
</table>
</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:
virtualScroller.invalidateAllCachedMeasurements();
virtualScroller.invalidateCachedMeasurementForItem(item: any);
virtualScroller.invalidateCachedMeasurementAtIndex(index: number);
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).
import { Component, ViewChild } from '@angular/core';
import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
@Component({
selector: 'rj-list',
template: `
<virtual-scroller [items]="items" (vsUpdate)="scrollList = $event">
<div *ngFor="let item of scrollList; let i = index"> {{i}}: {{item}} </div>
</virtual-scroller>
`
})
export class ListComponent {
protected items = ['Item1', 'Item2', 'Item3'];
@ViewChild(VirtualScrollerComponent)
private virtualScroller: VirtualScrollerComponent;
// call this function after resize + animation end
afterResize() {
this.virtualScroller.refresh();
}
}
You can use the scrollInto(item, alignToBeginning?, additionalOffset?, animationMilliseconds?, animationCompletedCallback?)
api to scroll into an item in the list.
You can also use the scrollToIndex(index, alignToBeginning?, additionalOffset?, animationMilliseconds?, animationCompletedCallback?)
api for the same purpose.
See below:
import { Component, ViewChild } from '@angular/core';
import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
@Component({
selector: 'rj-list',
template: `
<virtual-scroller [items]="items" (vsUpdate)="scrollList = $event">
<div *ngFor="let item of scrollList; let i = index"> {{i}}: {{item}} </div>
</virtual-scroller>
`
})
export class ListComponent {
protected items = ['Item1', 'Item2', 'Item3'];
@ViewChild(VirtualScrollerComponent)
private virtualScroller: VirtualScrollerComponent;
// call this function whenever you have to focus on second item
focusOnAnItem() {
this.virtualScroller.items = this.items;
this.virtualScroller.scrollInto(items[1]);
}
}
Some config settings can be set via DI, so you can set them globally instead of on each instance of virtual-scroller.
providers: [
{ provide: 'virtualScroller.scrollThrottlingTime', useValue: 0 },
{ provide: 'virtualScroller.scrollDebounceTime', useValue: 0 },
{ provide: 'virtualScroller.scrollAnimationTime', useValue: 750 },
{ provide: 'virtualScroller.scrollbarWidth', useValue: undefined },
{ provide: 'virtualScroller.scrollbarHeight', useValue: undefined },
{ provide: 'virtualScroller.checkResizeInterval', useValue: 1000 },
{ provide: 'virtualScroller.resizeBypassRefreshThreshold', useValue: 5 }
],
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:
sort() {
this.items = [].concat(this.items || []).sort()
}
This hacky CSS allows hiding a scrollbar while still enabling scroll through mouseWheel/touch/pageUpDownKeys
//hide vertical scrollbar
margin-right: -25px;
padding-right: 25px;
//hide horizontal scrollbar
margin-bottom: -25px;
padding-bottom: 25px;
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:
const domino = require('domino');
require('raf/polyfill');
const win = domino.createWindow(template);
win['versionNumber'] = 'development';
global['window'] = win;
global['document'] = win.document;
Object.defineProperty(win.document.body.style, 'transform', { value: () => { return { enumerable: true, configurable: true }; } });
<virtual-scroller #scroll [items]="items">
<my-custom-component *ngFor="let item of scroll.viewPortItems" [ssrChildWidth]="138" [ssrChildHeight]="175" [ssrViewportWidth]="1500" [ssrViewportHeight]="800">
</my-custom-component>
</virtual-scroller>
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.
FAQs
Angular module for virtual -infinite- list. Supports horizontal/vertical, variable heights, & multi-column
We found that ngx-virtual-scroller demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.