Giter Site home page Giter Site logo

rintoj / ngx-virtual-scroller Goto Github PK

View Code? Open in Web Editor NEW
977.0 31.0 292.0 34.52 MB

Virtual Scroll displays a virtual, "infinite" list.

Home Page: https://rintoj.github.io/ngx-virtual-scroller

License: MIT License

TypeScript 100.00%
infinite angular2 angular2-component virtual-scroll

ngx-virtual-scroller's Introduction

Sponsors

ngx-virtual-scroller

Virtual Scroll displays a virtual, "infinite" list. Supports horizontal/vertical, variable heights, & multi-column.

Renamed from angular2-virtual-scroll to ngx-virtual-scroller. Please update your package.json

About

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

Breaking Changes:

  • v3.0.0 Several 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.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 virtualScroller
  • v0.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.
    • viewPortIndices.arrayStartIndex renamed to viewPortIndices.startIndex and viewPortIndices.arrayEndIndex renamed to viewPortIndices.endIndex
  • 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.

New features:

  • RTL Support on Horizontal scrollers
  • Support for fixed <thead> on <table> elements.
  • Added API to query for current scroll px position (also passed as argument to IPageInfo listeners)
  • 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 [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.
  • 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)

Demo

See Demo Here

Usage

Preferred option:

<virtual-scroller #scroll [items]="items">
    <my-custom-component *ngFor="let item of scroll.viewPortItems">
    </my-custom-component>
</virtual-scroller>

option 2: note: viewPortItems must be a public field to work with AOT

<virtual-scroller [items]="items" (vsUpdate)="viewPortItems = $event">
    <my-custom-component *ngFor="let item of viewPortItems">
    </my-custom-component>
</virtual-scroller>

option 3: note: viewPortItems must be a public field to work with AOT

<div virtualScroller [items]="items" (vsUpdate)="viewPortItems = $event">
    <my-custom-component *ngFor="let item of viewPortItems">
    </my-custom-component>
</div>

Get Started

Step 1: Install ngx-virtual-scroller

npm install ngx-virtual-scroller

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 {
  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 angular 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>

Interfaces

interface IPageInfo {
	startIndex: number;
	endIndex: number;
	scrollStartPosition: number;
	scrollEndPosition: number;
	startIndexWithBuffer: number;
	endIndexWithBuffer: number;
	maxScrollPosition: number;
}

API

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 angular/angular#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.

<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.

Use scrollbar of window

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 with variable size

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>

Loading in chunks

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.

import { IPageInfo } from 'ngx-virtual-scroller';
...

@Component({
    selector: 'list-with-api',
    template: `
        <virtual-scroller #scroll [items]="buffer" (vsEnd)="fetchMore($event)">
            <my-custom-component *ngFor="let item of scroll.viewPortItems"> </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: IPageInfo) {
        if (event.endIndex !== 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) => {
            ....
        });
    }
}

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.

<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>

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.invalidateCachedMeasurementForItem(item: any);
virtualScroller.invalidateCachedMeasurementAtIndex(index: 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.

Example:

<virtual-scroller #scroll [items]="items">
    <my-custom-component [expanded]="item.expanded" *ngFor="let item of scroll.viewPortItems">
    </my-custom-component>
</virtual-scroller>

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 [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 #scroll [items]="items">
            <div *ngFor="let item of scroll.viewPortItems; 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();
    }
}

Focus an item

You can use the scrollInto() or scrollToIndex() API to scroll into an item in the list:

import { Component, ViewChild } from '@angular/core';
import { VirtualScrollerComponent } from 'ngx-virtual-scroller';

@Component({
    selector: 'rj-list',
    template: `
        <virtual-scroller #scroll [items]="items">
            <div *ngFor="let item of scroll.viewPortItems; 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]);
    }
}

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.

providers: [
    provide: 'virtual-scroller-default-options', useValue: {
        checkResizeInterval: 1000,
        modifyOverflowStyleOfParentScroll: true,
        resizeBypassRefreshThreshold: 5,
        scrollAnimationTime: 750,
        scrollDebounceTime: 0,
        scrollThrottlingTime: 0,
        stripedTable: false
    }
],

OR

export function vsDefaultOptionsFactory(): VirtualScrollerDefaultOptions {
    return {
        checkResizeInterval: 1000,
        modifyOverflowStyleOfParentScroll: true,
        resizeBypassRefreshThreshold: 5,
        scrollAnimationTime: 750,
        scrollDebounceTime: 0,
        scrollThrottlingTime: 0,
        stripedTable: false
    };
}

providers: [
    provide: 'virtual-scroller-default-options', useFactory: vsDefaultOptionsFactory
],

Sorting Items

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()
}

Hide Scrollbar

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;

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 #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>

Performance - TrackBy

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:

<virtual-scroller #scroll [items]="myComplexItems">
    <my-custom-component
        [myComplexItem]="complexItem"
        *ngFor="let complexItem of scroll.viewPortItems; trackBy: myTrackByFunction">
    </my-custom-component>
</virtual-scroller>
public interface IComplexItem {
    uniqueIdentifier: number;
    extraData: any;
}

public myTrackByFunction(index: number, complexItem: IComplexItem): number {
    return complexItem.uniqueIdentifier;
}

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 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

  1. avoid mutating state on any bound properties where possible &
  2. 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:

import { ChangeDetectorRef } from '@angular/core';

public class ManualChangeDetection {
    public queueChangeDetection(): void {
        this.changeDetectorRef.markForCheck(); // marks self for change detection on the next cycle, but doesn't actually schedule a cycle
        this.queueApplicationTick();
    }

    public static STATIC_APPLICATION_REF: ApplicationRef;
    public static queueApplicationTick: ()=> void = Util.debounce(() => {
        if (ManualChangeDetection.STATIC_APPLICATION_REF['_runningTick']) {
            return;
        }

        ManualChangeDetection.STATIC_APPLICATION_REF.tick();
    }, 5);

    constructor(private changeDetectorRef: ChangeDetectorRef) {
    }
}

// note: this portion is only needed if you don't already have a debounce implementation in your app
public class Util {
    public static throttleTrailing(func: Function, wait: number): Function {
        let timeout = undefined;
        let _arguments = undefined;
        const result = function () {
            const _this = this;
            _arguments = arguments;

            if (timeout) {
                return;
            }

            if (wait <= 0) {
                func.apply(_this, _arguments);
            } else {
                timeout = setTimeout(function () {
                    timeout = undefined;
                    func.apply(_this, _arguments);
                }, wait);
            }
        };
        result['cancel'] = function () {
            if (timeout) {
                clearTimeout(timeout);
                timeout = undefined;
            }
        };

        return result;
    }

    public static debounce(func: Function, wait: number): Function {
        const throttled = Util.throttleTrailing(func, wait);
        const result = function () {
            throttled['cancel']();
            throttled.apply(this, arguments);
        };
        result['cancel'] = function () {
            throttled['cancel']();
        };

        return result;
    }
}

public class MyEntryLevelAppComponent
{
    constructor(applicationRef: ApplicationRef) {
        ManualChangeDetection.STATIC_APPLICATION_REF = applicationRef;
    }
}

@Component({
	...
  changeDetection: ChangeDetectionStrategy.OnPush
	...
})
public class SomeRandomComponentWhichUsesOnPush {
    private manualChangeDetection: ManualChangeDetection;
    constructor(changeDetectorRef: ChangeDetectorRef) {
        this.manualChangeDetection = new ManualChangeDetection(changeDetectorRef);
    }

    public someFunctionThatMutatesState(): void {
        this.someBoundProperty = someNewValue;

        this.manualChangeDetection.queueChangeDetection();
    }
}

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 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:

import { ChangeDetectorRef } from '@angular/core';

public class MainComponent {
    constructor(public changeDetectorRef: ChangeDetectorRef) { }
}
<virtual-scroller
    #scroll
    [items]="items"
    [executeRefreshOutsideAngularZone]="true"
    (vsUpdate)="changeDetectorRef.detectChanges()"
>
    <my-custom-component *ngFor="let item of scroll.viewPortItems">
    </my-custom-component>
</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 - 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.

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

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:

  1. Use https://www.npmjs.com/package/domino and https://www.npmjs.com/package/raf polyfills in your main.server.ts file
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 }; } });
  1. 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.
  2. 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.
<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>

Known Issues

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 🙂

Nested Scrollbars

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.

Contributing

Contributions are very welcome! Just send a pull request. Feel free to contact me or checkout my GitHub page.

Authors

  • Rinto Jose (rintoj)
  • Devin Garner (speige)
  • Pavel Kukushkin (kykint)

Hope this module is helpful to you. Please make sure to checkout my other projects and articles. Enjoy coding!

Follow me: GitHub | Facebook | Twitter | Google+ | Youtube

Versions

Check CHANGELOG

License

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.

ngx-virtual-scroller's People

Contributors

a139383 avatar aaronfrost avatar abraham avatar antontrafimovich avatar colas74 avatar decline avatar dependabot[bot] avatar disist avatar hold-n avatar kntmrkm avatar kykint avatar marcelh1983 avatar mateusmeyer avatar mattlewis92 avatar mbcom avatar mehmet-erim avatar natcohen avatar noambuzaglo avatar pitmov avatar ribizli avatar rintoj avatar sharikovvladislav avatar speige avatar tolemac avatar uso5 avatar vanackere avatar whyboris avatar wmaurer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-virtual-scroller's Issues

No scrolling when adding items at the beginning

I'm trying to write a chat application with this library.
Unlike normal lists I have to add items to the beginning of the input array. I used the start event to trigger this update.
The problem is that the scroll view automatically scrolls to the top then. Which in turn triggers the start event again and so on.
Could you add a parameter to prevent this scrolling to top or give an example how to achieve the wanted behavior with the current release?
I already tried to use the scrollInto function after updating the input array but for some reason I created an infinite rendering loop.

Feature: Support Iterable

Please add support to Javascript iterables for the Itens property.
It's necessary for handling ImmutableJS Lists on Redux environments.

Incorrect behavior on items change

May be I miss something, I'm trying to use with angular 4 ngfor and updating items with mobx autorun.

Initially: one item (with zero doesn't work because of this) is displayed correctly.

Setting [items] to another array instance (initial concatenated with 15 items), all contained in viewport: not all items are displayed and shows vertical scroll bar that shouldn't be there.

It seems that countItemsPerRow is called only once after replace and at the time of the call there this.items.length is 16 but this.contentElementRef.nativeElement.children.length is 1. So it uses 1 item per row in calculations resulting in incorrect values.

Scroll is glitchy on iOS safari (Ionic 2)

I'm using this library as part of an Ionic 2 application. When running on an iOS device, we saw the below glitchy behavior.

Glitch on iOS safari

This is the template.

<virtual-scroll
    [items]="recipes"
    (change)="indices = $event"
    (update)="scrollItems = $event"
    style="height: 100%; display: block">
    <div *ngFor="let item of scrollItems" style="width: 100%">
      ...
    </div>
</virtual-scroll>

The used recipes variable starts out as an empty array and is updated after the API request observable is completed.

EDIT

Tried again with a much simpler content

  <virtual-scroll
    [items]="testItems"
    (change)="indices = $event"
    (update)="scrollItems = $event"
    style="height: 100%; display: block">
    <div *ngFor="let item of scrollItems" style="width: 100%">
      <ion-card style="height: 300px; width: 100%">
        <p>Item</p>
      </ion-card>
    </div>
  </virtual-scroll>

Still the problem is there.

Horizontal Scroll

Thank you for doing this!

Is it possible to do a horizontal scroll, something like this which uses VirtualScroll (non-angular)?

npm install fails

Downloading the repo and immediately running 'npm install' yields err!

'prepublish' seems to be firing, running 'build', then fails at 'tsc'...

[email protected] tsc c:\git\angular2-virtual-scroll
node_modules/typescript/bin/tsc

'node_modules' is not recognized as an internal or external command,
operable program or batch file.

npm -v 4.1.1 on windows

Loading rows after loaded 0 rows

I have a virtual scroll that is working fine but when the filter reduce the list to 0 elements, next time I change the source list to a list with elements, the virtual scroll only show 2 rows.
The problem is comeing in this part of code:

   if (this.childWidth == undefined || this.childHeight == undefined) {
            contentDimensions = content.children[0] ? content.children[0].getBoundingClientRect() : {
                width: viewWidth,
                height: viewHeight
            };
        }

When I load the last time the list, this part of code put height to the same height of the container... it's a bug. How could I fix it?

Infinite event loop with empty items array

If input array is empty the component enters infinite update event loop.

I think the reason is
if (start !== this.previousStart || end !== this.previousEnd) {
is always true when NaN value is involved.

The fix seems a bit more elaborate than just fixing the condition when no initial item sizes are given, it needs to re-init when going from empty to non-empty items and vice versa.

Unable to remove items from list

When trying to remove an item from the list, it's not removed until I scroll just a little.

I'm removing entries from the data using filter, which will create a new list, so the reference change should be in place.

I've tried triggering refresh() manually, no luck.

I'm having a hard time seeing how this does not work, when sorting seems to be somewhat similar.

Can I use the virtual scroll with a HTML table?

Is there any way to use this component with a table?

Something similar to:

    <virtual-scroll [items]="rows" [childHeight]="30">
      <tr *ngFor="let item of rows">
        <td>Some text</td>
      </tr>
    </virtual-scroll>

NPM packaging: missing source file virtual-scroll.ts

When including the npm module version 0.1.3 in my project I get an error:

WARNING in ./~/angular2-virtual-scroll/dist/virtual-scroll.js
Cannot find source file '../src/virtual-scroll.ts': Error: Can't resolve '../src/virtual-scroll.ts' in '/home/name/dev/test/node_modules/angular2-virtual-scroll/dist'

The dist folder contains:
virtual-scroll.d.ts
virtual-scroll.js
virtual-scroll.js.map
virtual-scroll.metadata.json

The src folder containing virtual-scroll.ts is not contained in the dist folder.

AoT compilation fails

When running AoT compilation ( node_modules/.bin/ngc -p tsconfig-aot.json ) it fails with the following error:

Unexpected value 'VirtualScrollModule in /node_modules/angular2-virtual-scroll/dist/virtual-scroll.d.ts' imported by the module 'AppModule in /app/app.module.ts'

tsconfig-aot.json

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "noImplicitAny": false,
    "sourceMap": true,
    "mapRoot": "",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "outDir": "lib",
    "skipLibCheck": true,
    "rootDir": ".",
	"typeRoots": [
      "node_modules/@types"
    ]
  },
  "angularCompilerOptions": {
    "genDir": "./app/ngfactory",
    "entryModule": "./app/app.module#AppModule"
  }
}

app.module.ts (excerpt)

import { VirtualScrollModule } from 'angular2-virtual-scroll';

@NgModule({
  imports: [
	VirtualScrollModule,
  ],
  declarations: [

  ],
  bootstrap: [ AppComponent ]
})

Observable input

Good day, I'ev just started trying out your virtual scroll and I'm having difficulities making it work with an observable collection.

<virtual-scroll [items]="persons" (update)="viewPortItems = $event"> <Contact *ngFor="let item of viewPortItems" [person]="item"></Contact> </virtual-scroll>

Where "persons" is an Observable<PersonModel[]>.
The HTML code works when I use mocked data.

Am I using it wrongly, not having it set up correctly, or is it simply not supported at this time?

BUG infinite request on (change)

I succed to use your module, FINALLY ! :)

I simply use your demo to load more chunk when scrolling but it seems big bug when scroll fast or drag scrollbar until bottom, look here my gif:

bug chunk load

code:

exactly the same as your demo

browser:

bug on chrome and firefox

Error in list item

Can't bind to 'item' since it isn't a known property of 'list-item'.

  1. If 'list-item' is an Angular component and it has 'item' input, then verify that it is part of this module.

Smooth scroll on webkit (mobile)

Enhancement (i'm writing from iphone)

Can you add thiss css to the container
-webkit-overflow-scrolling: touch;
To enable smooth scroll on phone
It will radically become more smoothly and ergonomic when scrolling on mobile :)

Thanks

Multiple Virtual Scroll and FlexBox

First of all I want to thank you for your nice module.
I am trying to implement your module in my project but I have difficulty with two things

  1. I can't manage to have multiple virtual scroll in one page. It seems some how they are repeating the same items which is the items of the last virtual scroll
  2. I am using Angular Flex Layout to size my items in the virtual scroll but it seems it doesn't detect the child size. Any recommendation?

Focusing element from top

Hi thanks updating docs for focusing on element. Function is handy, but it focusing on element at bottom of screen, I am talking about this line

this.element.nativeElement.scrollTop = Math.floor(index / d.itemsPerRow) * d.childHeight - Math.max(0, (d.itemsPerCol - 1)) * d.childHeight;

originally it should scroll to top of the item (correct me if i am wrong):

this.element.nativeElement.scrollTop = Math.floor(index / d.itemsPerRow) * d.childHeight;

Thanks for an answer.

No items are shown

Hi, there seems to be an issue that is causing the virtual-scroll calculation to fail.
See attached image. There are only 12 items in the full list, and each item height is around 38px. however the scrollbar-content has a translateY=632px, which is causing it to render nothing.
I'm not sure if it is related, seems to reproduce with small amount of items.

This is an awesome component 👍. However, with the current bug I'm a bit worried to use it in production :(

image

no found in my project

captura de pantalla 2017-03-20 a las 13 35 02

code:

<virtual-scroll [items]="cards" (update)="scrollItems = $event" >
<div *ngFor="let card of scrollItems" >{{card.dataevent.name}}</ div>
</ virtual-scroll>

data: from remote.

captura de pantalla 2017-03-20 a las 13 36 50

List elements with different heights don't work

I have a list with elements showing blog posts which all have very different heights (from 80px to, theoretically, infinity), there is also no way to know the height in advance because an individual post can contain many different media types. When I set the the childHeight to my minimum height of 80px as discribed in the README, I see the part of the post which fits on my screen, but as soon as I scroll more than 80px the list jumps to the start of the next post. Instead it should show the rest of the post, the same way it works in the example for constant height elements.

How to adjust childHeight?

I am using your list-with-api example component. It works just fine! However, I am trying to adjust the child height and I don't understand how to do this properly.

With your example there is no input [childHeight], so I changed :host height in list-item.scss, but this doesn't work well. I also tried adding [childHeight], but I just can't get it right. I probably don't understand the connection between the childHeight attribute and the css item height. What am I doing wrong here?

------- Adding a childWidth solved the problem ------

Scrolling performance can be improved with switchMap

I noticed that in lists with a large number of items rendered, scrolling up and down repeatedly causes chrome to become temporarily unresponsive when the user stops scrolling. During this time the memory also temporarily spikes. I think this is because chrome is busy garbage collecting all the rendered dom elements that were removed from the previous scroll events.

To improve performane, you can replace the following line in ngOnInit:

this.onScrollListener = this.renderer.listen(this.elRef.nativeElement, 'scroll', this.refresh.bind(this));

with the following:

scroll$: Subject<Event> = new Subject<Event>();
@HostListener('scroll')
onScroll(e: Event) {
    this.scroll$.next();
  }

ngOnInit() {
    this.scroll$.switchMap(() => {
      this.refresh();
      return Observable.of();
    }).subscribe(() => {});
    // other code ...
}

With this change, the rendering of items from previous scroll events gets canceled and chrome stays responsive and the memory stays constant.

angular cli use

I try to use your lib inside my angular-cli project your last version and I get :
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: VirtualScrollModule is not an NgModule

requestAnimationFrame?

I was under the impression that angular handles updates so we shouldn't need requestAnimationFrame.

I only noticed this because I use JSDOM to run my tests and the polyfill for this is not included in standard Angular CLI stuff. Also, I think the use of this is causing flicker and taking it out will remove that.

Using virtual scroll with api

Is it possible to use web api like github api, to fetch paginated results and at the end of scroll fetch next set of items etc?

Dont include Rx.js

Please dont include the whole Rx.js library, import the operators and object you need. Every app that imports you lib will automatically bundle 600kb of rxjs, in most cases we dont even need half of it.

And treeshaking will not save it cause rxjs imports operators via prototype.

Cheers

Safari Issue

In safari, when scrolling all the way up, it only shows two items out of many and then by scrolling a little bit back it suddenly pops all of them.
I had a look I noticed two things on safari:

  1. scrollable content translate goes to -440
  2. height of the virtual-scroll element it self changes when I scroll all the way up

Refresh Issues

Hi mate,

i have an issue when change items insiede virtual-scroll. First time it's work ok, then i change the [items] collection with a new array of object but only two items are designed. I tried call refresh() method but it's don't work.

issue

The problem is in calculateItems()
let indexByScrollTop = el.scrollTop / this.scrollHeight * d.itemCount / d.itemsPerRow;

el.scrollTop is wrong. Have you any idea?

external control of start index

Hi,

Thank you for your excellent component for virtual lists!

It will be cool if there is control over the starting position of the list.
By example - a "startIndex" input property.

About `end` event

Hi @rintoj,

what do you think about fire end event at startup if all elements are showed?

I'm using end event to load more items from a service, I load elements in groups of 10 items, however if the viewPort show the 10 firsts items without show scrollbar the end event never trigger.

What do you think about? Is this way by design?

If you are agree I could make a pullrequest ;)

scrolling multi column jumps if ending item is n+1 % columnCount > 0

At line 187 you check for maxStart in a way that assumes your items[] will always be evenly divisible by the number of items in each row. This causes the data to "jump" once you scroll to the bottom.

The fix for this is to adjust maxStart so that this doesn't happen.

        let maxStartEnd = end;
        let modEnd = end % d.itemsPerRow;
        if(modEnd) {
            maxStartEnd = end + d.itemsPerRow - modEnd;
        }
        var maxStart = Math.max(0, maxStartEnd - d.itemsPerCol * d.itemsPerRow - d.itemsPerRow);

viewport items not updating when items sorted.

Say I use a sort function, and I call the refresh fn. The data in view does not update. But as soon as I scroll once, the data in viewport gets updated. I tried, using virtualScroll.contentElementRef.nativeElement.scrollTop += 1, but that doesnt work as well.

Can you please help?

Scroll to item

Hi

I implemented virtual scroll to my project, it work perfectly. How can I scroll to certain item? Lets say i have sorted contact list and i need to jump to items by alphabet.

Thanks.

example of 1mio

your virtual scroll seems cool, can you make an example with 1mio :) or 100k rows ? This will show your perfs to users

enhancement: Does it supoprt AoT

great work

Does it work with tables?

Hi,

Your component looks great. I've tried it with lists and it does what it promises to.
However, I've tried using it for table rows, as you'll see below, but no rows are shown:

  <table class="table table-striped table-hover">
    <tr class="headerRow">
      <th *ngFor="let field of fields">{{field.label}}</th>
    </tr>
    <virtual-scroll [items]="data" (update)="viewPortItems = $event">
      <tr *ngFor="let entry of viewPortItems">
        <td *ngFor="let field of fields">
          <date-entry *ngIf="field.type === 'date'" [value]="entry[field.propertyName]" [format]="field.formatter" [filterTerm]="filterTerm"></date-entry>
          <string-entry *ngIf="field.type === 'string'" [value]="entry[field.propertyName]" [filterTerm]="filterTerm"></string-entry>
        </td>
      </tr>
    </virtual-scroll>
  </table>

Need help/suggestion: "bottom-up direction"

Hi,

The component seems to work just fine in normal situations where a list is displayed from top to bottom; However, in my use case, I need to flip the whole thing; Think of a chat, where the first message is at the top, and last is at the bottom (which means the scrollbar needs to stay at the bottom too)

I iterate over my collection normally and planned to use Flexbox to reorder the messages on the screen. Obviously, the VS component isn't aware of that and all sort of weird things happens

One "crazy" solution I though about was to use CSS transform to rotate the whole container 180deg, then each repeated item 180deg as well; That probably would work but then the mouse scroll direction would also be upside down...

I'm still trying to figure out a simple solution but haven't got around anything yet. Maybe someone will have an idea about this?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.