@ahmedhfarag/ngx-virtual-scroller 4.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,808 @@
1
+ # Sponsors
2
+
3
+ <table>
4
+ <tbody>
5
+ <tr>
6
+ <td align="center" valign="middle">
7
+ <a href="https://moviepix.app/?utm_source=sponsor&utm_campaign=ngx-virtual-scroller" target="_blank">
8
+ <img src="https://moviepix.app/images/Logo_Small.png">
9
+ <img src="https://moviepix.app/images/Title_Small.png">
10
+ </a>
11
+ </td>
12
+ </tr>
13
+ </tbody>
14
+ </table>
15
+
16
+ # ngx-virtual-scroller
17
+
18
+ Virtual Scroll displays a virtual, "infinite" list. Supports horizontal/vertical, variable heights, & multi-column.
19
+
20
+ ## Renamed from `angular2-virtual-scroll` to `ngx-virtual-scroller`. Please update your _package.json_
21
+
22
+ ## About
23
+
24
+ This module displays a small subset of records just enough to fill the viewport and uses the same DOM elements as the user scrolls.
25
+ 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.
26
+
27
+ - Supports multi-column
28
+ - Easy to use APIs
29
+ - Open source and available in GitHub
30
+
31
+ ## Breaking Changes:
32
+
33
+ - `v3.0.0` Several deprecated properties removed (see changelog).
34
+ - 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.
35
+ - `v2.1.0` Dependency Injection syntax was changed.
36
+ - `v1.0.6` viewPortIndices API property removed. (use viewPortInfo instead)
37
+ - `v1.0.3` Renamed everything from _virtual-scroll_ to _virtual-scroller_ and from _virtualScroll_ to _virtualScroller_
38
+ - `v0.4.13` _resizeBypassRefreshTheshold_ renamed to _resizeBypassRefreshThreshold_ (typo)
39
+ - `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.
40
+ - viewPortIndices.arrayStartIndex renamed to viewPortIndices.startIndex and viewPortIndices.arrayEndIndex renamed to viewPortIndices.endIndex
41
+ - `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)
42
+
43
+ *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.
44
+
45
+ ## New features:
46
+
47
+ - RTL Support on Horizontal scrollers
48
+ - Support for fixed `<thead>` on `<table>` elements.
49
+ - Added API to query for current scroll px position (also passed as argument to `IPageInfo` listeners)
50
+ - Added API to invalidate cached child item measurements (if your child item sizes change dynamically)
51
+ - Added API to scroll to specific px position
52
+ - If scroll container resizes, the items will auto-refresh. Can be disabled if it causes any performance issues by setting `[checkResizeInterval]="0"`
53
+ - `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.
54
+ - Support for horizontal scrollbars
55
+ - Support for elements with different sizes
56
+ - Added ability to put other elements inside of scroll (Need to wrap list itself in @ContentChild('container'))
57
+ - Added ability to use any parent with scrollbar instead of this element (@Input() parentScroll)
58
+
59
+ ## Demo
60
+
61
+ [See Demo Here](http://rintoj.github.io/ngx-virtual-scroller)
62
+
63
+ ## Usage
64
+
65
+ Preferred option:
66
+ ```html
67
+ <virtual-scroller #scroll [items]="items">
68
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
69
+ </my-custom-component>
70
+ </virtual-scroller>
71
+ ```
72
+
73
+ option 2:
74
+ note: viewPortItems must be a public field to work with AOT
75
+ ```html
76
+ <virtual-scroller [items]="items" (vsUpdate)="viewPortItems = $event">
77
+ <my-custom-component *ngFor="let item of viewPortItems">
78
+ </my-custom-component>
79
+ </virtual-scroller>
80
+ ```
81
+
82
+ option 3:
83
+ note: viewPortItems must be a public field to work with AOT
84
+ ```html
85
+ <div virtualScroller [items]="items" (vsUpdate)="viewPortItems = $event">
86
+ <my-custom-component *ngFor="let item of viewPortItems">
87
+ </my-custom-component>
88
+ </div>
89
+ ```
90
+
91
+ ## Get Started
92
+
93
+ **Step 1:** Install ngx-virtual-scroller
94
+
95
+ ```sh
96
+ npm install ngx-virtual-scroller
97
+ ```
98
+
99
+ **Step 2:** Import virtual scroll module into your app module
100
+
101
+ ```ts
102
+ ....
103
+ import { VirtualScrollerModule } from 'ngx-virtual-scroller';
104
+
105
+ ....
106
+
107
+ @NgModule({
108
+ ...
109
+ imports: [
110
+ ....
111
+ VirtualScrollerModule
112
+ ],
113
+ ....
114
+ })
115
+ export class AppModule { }
116
+ ```
117
+
118
+ **Step 3:** Wrap _virtual-scroller_ tag around elements;
119
+
120
+ ```html
121
+ <virtual-scroller #scroll [items]="items">
122
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
123
+ </my-custom-component>
124
+ </virtual-scroller>
125
+ ```
126
+
127
+ You must also define width and height for the container and for its children.
128
+
129
+ ```css
130
+ virtual-scroller {
131
+ width: 350px;
132
+ height: 200px;
133
+ }
134
+
135
+ my-custom-component {
136
+ display: block;
137
+ width: 100%;
138
+ height: 30px;
139
+ }
140
+ ```
141
+
142
+ **Step 4:** Create `my-custom-component` component.
143
+
144
+ `my-custom-component` must be a custom _angular_ component, outside of this library.
145
+
146
+ Child component is not necessary if your item is simple enough. See below.
147
+
148
+ ```html
149
+ <virtual-scroller #scroll [items]="items">
150
+ <div *ngFor="let item of scroll.viewPortItems">{{item?.name}}</div>
151
+ </virtual-scroller>
152
+ ```
153
+
154
+ ## Interfaces
155
+ ```ts
156
+ interface IPageInfo {
157
+ startIndex: number;
158
+ endIndex: number;
159
+ scrollStartPosition: number;
160
+ scrollEndPosition: number;
161
+ startIndexWithBuffer: number;
162
+ endIndexWithBuffer: number;
163
+ maxScrollPosition: number;
164
+ }
165
+ ```
166
+
167
+ ## API
168
+
169
+ In _alphabetical_ order:
170
+
171
+ | Attribute | `Type` & Default | Description
172
+ |------------------------------------|-------------------|--------------|
173
+ | 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.
174
+ | checkResizeInterval | `number` 1000 | How often in milliseconds to check if _virtual-scroller_ (or parentScroll) has been resized. If resized, it'll call `Refresh()` method
175
+ | 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`).
176
+ | enableUnequalChildrenSizes | `boolean` false | If you want to use the "unequal size" children feature. This is not perfect, but hopefully "close-enough" for most situations.
177
+ | 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.
178
+ | horizontal | `boolean` false | Whether the scrollbars should be vertical or horizontal.
179
+ | invalidateAllCachedMeasurements | `Function` | `()=>void` - to force re-measuring *all* cached item sizes. If `enableUnequalChildrenSizes===false`, only 1 item will be re-measured.
180
+ | invalidateCachedMeasurementAtIndex | `Function` | `(index:number)=>void` - to force re-measuring cached item size.
181
+ | invalidateCachedMeasurementForItem | `Function` | `(item:any)=>void` - to force re-measuring cached item size.
182
+ | 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.
183
+ | 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'.
184
+ | parentScroll | Element / Window | Element (or window), which will have scrollbar. This element must be one of the parents of virtual-scroller
185
+ | refresh | `Function` | `()=>void` - to force re-rendering of current items in viewport.
186
+ | RTL | `boolean` false | Set to `true` if you want horizontal slider to support right to left script (RTL).
187
+ | resizeBypassRefreshThreshold | `number` 5 | How many pixels to ignore during resize check if _virtual-scroller_ (or parentScroll) are only resized by a very small amount.
188
+ | scrollAnimationTime | `number` 750 | The time in milliseconds for the scroll animation to run for. 0 will completely disable the tween/animation.
189
+ | scrollDebounceTime | `number` 0 | Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons).
190
+ | scrollInto | `Function` | `(item:any, alignToBeginning:boolean = true, additionalOffset:number = 0, animationMilliseconds:number = undefined, animationCompletedCallback:()=>void = undefined)=>void` - Scrolls to item
191
+ | scrollThrottlingTime | `number` 0 | Milliseconds to delay refreshing viewport if user is scrolling quickly (for performance reasons).
192
+ | scrollToIndex | `Function` | `(index:number, alignToBeginning:boolean = true, additionalOffset:number = 0, animationMilliseconds:number = undefined, animationCompletedCallback:()=>void = undefined)=>void` - Scrolls to item at index
193
+ | scrollToPosition | `Function` | `(scrollPosition:number, animationMilliseconds:number = undefined, animationCompletedCallback: ()=>void = undefined)=>void` - Scrolls to px position
194
+ | 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.
195
+ | 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.
196
+ | ssrChildHeight | `number` | The hard-coded height of the item template's cell to use if rendering via _Angular Universal/Server-Side-Rendering_
197
+ | ssrChildWidth | `number` | The hard-coded width of the item template's cell to use if rendering via _Angular Universal/Server-Side-Rendering_
198
+ | ssrViewportHeight | `number` 1080 | The hard-coded visible height of the _virtual-scroller_ (or [parentScroll]) to use if rendering via _Angular Universal/Server-Side-Rendering_.
199
+ | ssrViewportWidth | `number` 1920 | The hard-coded visible width of the _virtual-scroller_ (or [parentScroll]) to use if rendering via _Angular Universal/Server-Side-Rendering_.
200
+ | 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.
201
+ | 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.
202
+ | viewPortInfo | `IPageInfo` | Allows querying the the current viewport info on demand rather than listening for events.
203
+ | viewPortItems | any[] | The array of items currently being rendered to the viewport.
204
+ | vsChange | `Event<IPageInfo>`| This event is fired every time the `start` or `end` indexes or scroll position change and emits `IPageInfo`.
205
+ | vsEnd | `Event<IPageInfo>`| This event is fired every time `end` index changes and emits `IPageInfo`.
206
+ | vsStart | `Event<IPageInfo>`| This event is fired every time `start` index changes and emits `IPageInfo`.
207
+ | 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>`
208
+ | 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.)
209
+ | 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.)
210
+
211
+ *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
212
+
213
+ 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.
214
+
215
+ ## Use parent scrollbar
216
+
217
+ If you want to use the scrollbar of a parent element, set `parentScroll` to a native DOM element.
218
+
219
+ ```html
220
+ <div #scrollingBlock>
221
+ <virtual-scroller #scroll [items]="items" [parentScroll]="scrollingBlock">
222
+ <input type="search">
223
+ <div #container>
224
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
225
+ </my-custom-component>
226
+ </div>
227
+ </virtual-scroller>
228
+ </div>
229
+ ```
230
+
231
+ 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.
232
+
233
+ ```html
234
+ <custom-angular-component #scrollingBlock>
235
+ <virtual-scroller #scroll [items]="items" [parentScroll]="scrollingBlock.nativeElement">
236
+ <input type="search">
237
+ <div #container>
238
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
239
+ </my-custom-component>
240
+ </div>
241
+ </virtual-scroller>
242
+ </custom-angular-component>
243
+ ```
244
+
245
+ *Note* - The parent element should have a width and height defined.
246
+
247
+ ## Use scrollbar of window
248
+
249
+ If you want to use the window's scrollbar, set `parentScroll`.
250
+
251
+ ```html
252
+ <virtual-scroller #scroll [items]="items" [parentScroll]="scroll.window">
253
+ <input type="search">
254
+ <div #container>
255
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
256
+ </my-custom-component>
257
+ </div>
258
+ </virtual-scroller>
259
+ ```
260
+
261
+ ## Items with variable size
262
+
263
+ Items _must_ have fixed height and width for this module to work perfectly. If not, set `[enableUnequalChildrenSizes]="true"`.
264
+
265
+ *(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.
266
+
267
+ ```html
268
+ <virtual-scroller #scroll [items]="items" [enableUnequalChildrenSizes]="true">
269
+
270
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
271
+ </my-custom-component>
272
+
273
+ </virtual-scroller>
274
+ ```
275
+
276
+ ## Loading in chunks
277
+
278
+ 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.
279
+
280
+ ```ts
281
+ import { IPageInfo } from 'ngx-virtual-scroller';
282
+ ...
283
+
284
+ @Component({
285
+ selector: 'list-with-api',
286
+ template: `
287
+ <virtual-scroller #scroll [items]="buffer" (vsEnd)="fetchMore($event)">
288
+ <my-custom-component *ngFor="let item of scroll.viewPortItems"> </my-custom-component>
289
+ <div *ngIf="loading" class="loader">Loading...</div>
290
+ </virtual-scroller>
291
+ `
292
+ })
293
+ export class ListWithApiComponent implements OnChanges {
294
+
295
+ @Input()
296
+ items: ListItem[];
297
+
298
+ protected buffer: ListItem[] = [];
299
+ protected loading: boolean;
300
+
301
+ protected fetchMore(event: IPageInfo) {
302
+ if (event.endIndex !== this.buffer.length-1) return;
303
+ this.loading = true;
304
+ this.fetchNextChunk(this.buffer.length, 10).then(chunk => {
305
+ this.buffer = this.buffer.concat(chunk);
306
+ this.loading = false;
307
+ }, () => this.loading = false);
308
+ }
309
+
310
+ protected fetchNextChunk(skip: number, limit: number): Promise<ListItem[]> {
311
+ return new Promise((resolve, reject) => {
312
+ ....
313
+ });
314
+ }
315
+ }
316
+ ```
317
+
318
+ ## With HTML Table
319
+
320
+ *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.
321
+
322
+ ```html
323
+ <virtual-scroller #scroll [items]="myItems">
324
+ <table>
325
+ <thead #header>
326
+ <th>Index</th>
327
+ <th>Name</th>
328
+ <th>Gender</th>
329
+ <th>Age</th>
330
+ <th>Address</th>
331
+ </thead>
332
+ <tbody #container>
333
+ <tr *ngFor="let item of scroll.viewPortItems">
334
+ <td>{{item.index}}</td>
335
+ <td>{{item.name}}</td>
336
+ <td>{{item.gender}}</td>
337
+ <td>{{item.age}}</td>
338
+ <td>{{item.address}}</td>
339
+ </tr>
340
+ </tbody>
341
+ </table>
342
+ </virtual-scroller>
343
+ ```
344
+
345
+ ## If child size changes
346
+ _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.
347
+
348
+ 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:
349
+ ```ts
350
+ virtualScroller.invalidateAllCachedMeasurements();
351
+ virtualScroller.invalidateCachedMeasurementForItem(item: any);
352
+ virtualScroller.invalidateCachedMeasurementAtIndex(index: number);
353
+ ```
354
+
355
+ ## If child view state is reverted after scrolling away & back
356
+ _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.
357
+
358
+ 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.
359
+
360
+ 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.
361
+
362
+ 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.
363
+
364
+ Example:
365
+ ```html
366
+ <virtual-scroller #scroll [items]="items">
367
+ <my-custom-component [expanded]="item.expanded" *ngFor="let item of scroll.viewPortItems">
368
+ </my-custom-component>
369
+ </virtual-scroller>
370
+ ```
371
+
372
+ ## If container size changes
373
+
374
+ *Note* - This should now be auto-detected, however the 'refresh' method can still force it if neeeded.
375
+
376
+ 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"`
377
+
378
+ Performance will be improved once "Resize Observer" (https://wicg.github.io/ResizeObserver/) is fully implemented.
379
+
380
+ Refresh method *(DEPRECATED)*
381
+
382
+ 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).
383
+
384
+ ```ts
385
+ import { Component, ViewChild } from '@angular/core';
386
+ import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
387
+
388
+ @Component({
389
+ selector: 'rj-list',
390
+ template: `
391
+ <virtual-scroller #scroll [items]="items">
392
+ <div *ngFor="let item of scroll.viewPortItems; let i = index">
393
+ {{i}}: {{item}}
394
+ </div>
395
+ </virtual-scroller>
396
+ `
397
+ })
398
+ export class ListComponent {
399
+
400
+ protected items = ['Item1', 'Item2', 'Item3'];
401
+
402
+ @ViewChild(VirtualScrollerComponent)
403
+ private virtualScroller: VirtualScrollerComponent;
404
+
405
+ // call this function after resize + animation end
406
+ afterResize() {
407
+ this.virtualScroller.refresh();
408
+ }
409
+ }
410
+ ```
411
+
412
+ ## Focus an item
413
+
414
+ You can use the `scrollInto()` or `scrollToIndex()` API to scroll into an item in the list:
415
+
416
+ ```ts
417
+ import { Component, ViewChild } from '@angular/core';
418
+ import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
419
+
420
+ @Component({
421
+ selector: 'rj-list',
422
+ template: `
423
+ <virtual-scroller #scroll [items]="items">
424
+ <div *ngFor="let item of scroll.viewPortItems; let i = index">
425
+ {{i}}: {{item}}
426
+ </div>
427
+ </virtual-scroller>
428
+ `
429
+ })
430
+ export class ListComponent {
431
+
432
+ protected items = ['Item1', 'Item2', 'Item3'];
433
+
434
+ @ViewChild(VirtualScrollerComponent)
435
+ private virtualScroller: VirtualScrollerComponent;
436
+
437
+ // call this function whenever you have to focus on second item
438
+ focusOnAnItem() {
439
+ this.virtualScroller.items = this.items;
440
+ this.virtualScroller.scrollInto(items[1]);
441
+ }
442
+ }
443
+ ```
444
+
445
+ ## Dependency Injection of configuration settings
446
+
447
+ Some default config settings can be overridden via DI, so you can set them globally instead of on each instance of _virtual-scroller_.
448
+
449
+ ```ts
450
+ providers: [
451
+ provide: 'virtual-scroller-default-options', useValue: {
452
+ checkResizeInterval: 1000,
453
+ modifyOverflowStyleOfParentScroll: true,
454
+ resizeBypassRefreshThreshold: 5,
455
+ scrollAnimationTime: 750,
456
+ scrollDebounceTime: 0,
457
+ scrollThrottlingTime: 0,
458
+ stripedTable: false
459
+ }
460
+ ],
461
+ ```
462
+
463
+ OR
464
+
465
+ ```ts
466
+ export function vsDefaultOptionsFactory(): VirtualScrollerDefaultOptions {
467
+ return {
468
+ checkResizeInterval: 1000,
469
+ modifyOverflowStyleOfParentScroll: true,
470
+ resizeBypassRefreshThreshold: 5,
471
+ scrollAnimationTime: 750,
472
+ scrollDebounceTime: 0,
473
+ scrollThrottlingTime: 0,
474
+ stripedTable: false
475
+ };
476
+ }
477
+
478
+ providers: [
479
+ provide: 'virtual-scroller-default-options', useFactory: vsDefaultOptionsFactory
480
+ ],
481
+ ```
482
+
483
+ ## Sorting Items
484
+
485
+ 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:
486
+
487
+ ```ts
488
+ sort() {
489
+ this.items = [].concat(this.items || []).sort()
490
+ }
491
+ ```
492
+
493
+ ## Hide Scrollbar
494
+
495
+ This hacky CSS allows hiding a scrollbar while still enabling scroll through mouseWheel/touch/pageUpDownKeys
496
+ ```scss
497
+ // hide vertical scrollbar
498
+ margin-right: -25px;
499
+ padding-right: 25px;
500
+
501
+ // hide horizontal scrollbar
502
+ margin-bottom: -25px;
503
+ padding-bottom: 25px;
504
+ ```
505
+
506
+ ## Additional elements in scroll
507
+
508
+ 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`.
509
+
510
+ ```html
511
+ <virtual-scroller #scroll [items]="items">
512
+ <input type="search">
513
+ <div #container>
514
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
515
+ </my-custom-component>
516
+ </div>
517
+ </virtual-scroller>
518
+ ```
519
+
520
+ ## Performance - TrackBy
521
+
522
+ _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.
523
+
524
+ 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.
525
+
526
+ A trackBy function must return either a number or string as a unique identifier for your object.
527
+
528
+ 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.
529
+
530
+ If the array used by `*ngFor` is of type `any[]`, you must code your own trackBy function.
531
+
532
+ Here's an example of how to do this:
533
+
534
+ ```html
535
+ <virtual-scroller #scroll [items]="myComplexItems">
536
+ <my-custom-component
537
+ [myComplexItem]="complexItem"
538
+ *ngFor="let complexItem of scroll.viewPortItems; trackBy: myTrackByFunction">
539
+ </my-custom-component>
540
+ </virtual-scroller>
541
+ ```
542
+
543
+ ```ts
544
+ public interface IComplexItem {
545
+ uniqueIdentifier: number;
546
+ extraData: any;
547
+ }
548
+
549
+ public myTrackByFunction(index: number, complexItem: IComplexItem): number {
550
+ return complexItem.uniqueIdentifier;
551
+ }
552
+ ```
553
+
554
+ ## Performance - ChangeDetection
555
+
556
+ _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.
557
+ Below is an explanation of how to correct your code. This will make your entire app much faster, including _virtual-scroller_.
558
+
559
+ 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.
560
+ This makes it easier for programmers to code apps, but also makes apps extremely slow.
561
+
562
+ If _virtual-scroller_ feels slow, a possible quick solution that masks the real problem is to use `scrollThrottlingTime` or `scrollDebounceTime` APIs.
563
+
564
+ 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`.
565
+
566
+ 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.
567
+ OnPush is much harder for the programmer to code. You have to code things differently: This means
568
+ 1) avoid mutating state on any bound properties where possible &
569
+ 2) manually running change detection when you do mutate state.
570
+ OnPush can be done on a component-by-component basis, however I recommend doing it for *EVERY* component in your app.
571
+
572
+ 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_.
573
+
574
+ My personal suggestion on the easiest way to implement _OnPush_ across your entire app:
575
+ ```ts
576
+ import { ChangeDetectorRef } from '@angular/core';
577
+
578
+ public class ManualChangeDetection {
579
+ public queueChangeDetection(): void {
580
+ this.changeDetectorRef.markForCheck(); // marks self for change detection on the next cycle, but doesn't actually schedule a cycle
581
+ this.queueApplicationTick();
582
+ }
583
+
584
+ public static STATIC_APPLICATION_REF: ApplicationRef;
585
+ public static queueApplicationTick: ()=> void = Util.debounce(() => {
586
+ if (ManualChangeDetection.STATIC_APPLICATION_REF['_runningTick']) {
587
+ return;
588
+ }
589
+
590
+ ManualChangeDetection.STATIC_APPLICATION_REF.tick();
591
+ }, 5);
592
+
593
+ constructor(private changeDetectorRef: ChangeDetectorRef) {
594
+ }
595
+ }
596
+
597
+ // note: this portion is only needed if you don't already have a debounce implementation in your app
598
+ public class Util {
599
+ public static throttleTrailing(func: Function, wait: number): Function {
600
+ let timeout = undefined;
601
+ let _arguments = undefined;
602
+ const result = function () {
603
+ const _this = this;
604
+ _arguments = arguments;
605
+
606
+ if (timeout) {
607
+ return;
608
+ }
609
+
610
+ if (wait <= 0) {
611
+ func.apply(_this, _arguments);
612
+ } else {
613
+ timeout = setTimeout(function () {
614
+ timeout = undefined;
615
+ func.apply(_this, _arguments);
616
+ }, wait);
617
+ }
618
+ };
619
+ result['cancel'] = function () {
620
+ if (timeout) {
621
+ clearTimeout(timeout);
622
+ timeout = undefined;
623
+ }
624
+ };
625
+
626
+ return result;
627
+ }
628
+
629
+ public static debounce(func: Function, wait: number): Function {
630
+ const throttled = Util.throttleTrailing(func, wait);
631
+ const result = function () {
632
+ throttled['cancel']();
633
+ throttled.apply(this, arguments);
634
+ };
635
+ result['cancel'] = function () {
636
+ throttled['cancel']();
637
+ };
638
+
639
+ return result;
640
+ }
641
+ }
642
+
643
+ public class MyEntryLevelAppComponent
644
+ {
645
+ constructor(applicationRef: ApplicationRef) {
646
+ ManualChangeDetection.STATIC_APPLICATION_REF = applicationRef;
647
+ }
648
+ }
649
+
650
+ @Component({
651
+ ...
652
+ changeDetection: ChangeDetectionStrategy.OnPush
653
+ ...
654
+ })
655
+ public class SomeRandomComponentWhichUsesOnPush {
656
+ private manualChangeDetection: ManualChangeDetection;
657
+ constructor(changeDetectorRef: ChangeDetectorRef) {
658
+ this.manualChangeDetection = new ManualChangeDetection(changeDetectorRef);
659
+ }
660
+
661
+ public someFunctionThatMutatesState(): void {
662
+ this.someBoundProperty = someNewValue;
663
+
664
+ this.manualChangeDetection.queueChangeDetection();
665
+ }
666
+ }
667
+ ```
668
+ 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.
669
+
670
+ ## Performance - executeRefreshOutsideAngularZone
671
+
672
+ 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.
673
+
674
+ `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`.
675
+
676
+ If you've correctly implemented `ChangeDetectionStrategy.OnPush` for 100% of your components, the `executeRefreshOutsideAngularZone` will not provide any performance benefit.
677
+
678
+ 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.
679
+
680
+ In this case you can get a free/easy performance boost with the following code:
681
+ ```ts
682
+ import { ChangeDetectorRef } from '@angular/core';
683
+
684
+ public class MainComponent {
685
+ constructor(public changeDetectorRef: ChangeDetectorRef) { }
686
+ }
687
+ ```
688
+
689
+ ```html
690
+ <virtual-scroller
691
+ #scroll
692
+ [items]="items"
693
+ [executeRefreshOutsideAngularZone]="true"
694
+ (vsUpdate)="changeDetectorRef.detectChanges()"
695
+ >
696
+ <my-custom-component *ngFor="let item of scroll.viewPortItems">
697
+ </my-custom-component>
698
+ </virtual-scroller>
699
+ ```
700
+
701
+ *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.
702
+
703
+ *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.
704
+
705
+ :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.
706
+
707
+ *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.
708
+
709
+ *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.
710
+
711
+ 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_.
712
+
713
+ ## Performance - scrollDebounceTime / scrollThrottlingTime
714
+
715
+ 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.
716
+
717
+ Without these set, _virtual-scroller_ will refresh immediately whenever the user scrolls.
718
+ 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.
719
+ Debounce won't refresh until the user has stopped scrolling for _# milliseconds_.
720
+ If both Debounce & Throttling are set, debounce takes precedence.
721
+
722
+ *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.
723
+
724
+ ## Angular Universal / Server-Side Rendering
725
+
726
+ 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).
727
+
728
+ _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.
729
+
730
+ 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:
731
+ 1) Use https://www.npmjs.com/package/domino and https://www.npmjs.com/package/raf polyfills in your `main.server.ts` file
732
+ ```ts
733
+ const domino = require('domino');
734
+ require('raf/polyfill');
735
+ const win = domino.createWindow(template);
736
+ win['versionNumber'] = 'development';
737
+ global['window'] = win;
738
+ global['document'] = win.document;
739
+ Object.defineProperty(win.document.body.style, 'transform', { value: () => { return { enumerable: true, configurable: true }; } });
740
+ ```
741
+ 2) 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.
742
+ 3) 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 `[ssrChildWidth]`/`[ssrChildHeight]`/`[ssrViewportWidth]`/`[ssrViewportHeight]` properties.
743
+ ```html
744
+ <virtual-scroller #scroll [items]="items">
745
+
746
+ <my-custom-component
747
+ *ngFor="let item of scroll.viewPortItems"
748
+ [ssrChildWidth]="138"
749
+ [ssrChildHeight]="175"
750
+ [ssrViewportWidth]="1500"
751
+ [ssrViewportHeight]="800"
752
+ >
753
+ </my-custom-component>
754
+
755
+ </virtual-scroller>
756
+ ```
757
+
758
+ ## Known Issues
759
+ 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:
760
+
761
+ ### Nested Scrollbars
762
+ 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.
763
+
764
+ ## Contributing
765
+ Contributions are very welcome! Just send a pull request. Feel free to contact me or checkout my [GitHub](https://github.com/rintoj) page.
766
+
767
+ ## Authors
768
+
769
+ * **Rinto Jose** (rintoj)
770
+ * **Devin Garner** (speige)
771
+ * **Pavel Kukushkin** (kykint)
772
+
773
+ ### Hope this module is helpful to you. Please make sure to checkout my other [projects](https://github.com/rintoj) and [articles](https://medium.com/@rintoj). Enjoy coding!
774
+
775
+ Follow me:
776
+ [GitHub](https://github.com/rintoj)
777
+ | [Facebook](https://www.facebook.com/rinto.jose)
778
+ | [Twitter](https://twitter.com/rintoj)
779
+ | [Google+](https://plus.google.com/+RintoJoseMankudy)
780
+ | [Youtube](https://youtube.com/+RintoJoseMankudy)
781
+
782
+ ## Versions
783
+ [Check CHANGELOG](https://github.com/rintoj/ngx-virtual-scroller/blob/master/CHANGELOG.md)
784
+
785
+ ## License
786
+ ```
787
+ The MIT License (MIT)
788
+
789
+ Copyright (c) 2016 Rinto Jose (rintoj)
790
+
791
+ Permission is hereby granted, free of charge, to any person obtaining a copy
792
+ of this software and associated documentation files (the "Software"), to deal
793
+ in the Software without restriction, including without limitation the rights
794
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
795
+ copies of the Software, and to permit persons to whom the Software is
796
+ furnished to do so, subject to the following conditions:
797
+
798
+ The above copyright notice and this permission notice shall be included in
799
+ all copies or substantial portions of the Software.
800
+
801
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
802
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
803
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
804
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
805
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
806
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
807
+ THE SOFTWARE.
808
+ ```