bhall bhall - 23 days ago 21
TypeScript Question

Angular2/Typescript Pull to Refresh

I am currently using Angular2/Typescript/PhoneGap on a mobile project, and attempting to use Angular2 to achieve Pull to Refresh functionality. Unfortunately, I'm unable to use Onsenui, Ionic, or jQuery for the solution due to project constraints.

As a rather new Angular dev (I'm a Junior Dev in general), I've been unable to find any examples that are in Angular2/Typescript (and don't use the above frameworks). Most of the existing libraries seem to be Angular1 and abandoned. See here and here.

My question is this: does anyone know of any Angular2 examples I can learn from or alternate solutions to accomplish this? And if not, is my best option to learn Angular1 well enough to convert one of these abandoned projects to Angular2?

Answer

You definitely should take a look to the basics of angular 1. Since angular2 is still young, in the future, you may have to implement some features not already available . For now, i created a naive implementation of the first library that you linked.

@Component({
    selector: 'ptr-container',
    styles: [`
        :host {
            display: block;
            max-height: 50px;
            overflow: auto;
        }
    `],
    template: `
        <section [hidden]="!inProgress">
            refresh in progress ... (change it by your own loader)
        </section>
        <ng-content></ng-content>
    `
})
export class PullToRefreshComponent {
    private lastScrollTop:number = 0;
    private isAtTop:boolean = false;
    private element:any;

    @Input('refresh') inProgress:boolean = false;
    @Output() onPull:EventEmitter<any> = new EventEmitter<any>();

    constructor(el:ElementRef) {
        this.element = el.nativeElement;
    }

    private get scrollTop() { return this.element.scrollTop || 0; }

    @HostListener('scroll')
    @HostListener('touchmove')
    onScroll() {
        if(this.scrollTop <= 0 && this.lastScrollTop <= 0) {
            if(this.isAtTop) this.onPull.emit(true);
            else this.isAtTop = true;
        }
        this.lastScrollTop = this.scrollTop;
    }

}

And here is a basic usage

@Component({
    selector: 'app',
    template: `
        <ptr-container (onPull)="onPull()" [refresh]="isInProgress"></ptr-container>
    `
})
export class AppComponent {

    isInProgress:boolean = false;

    onPull() {
        this.isInProgress = true;
    }

}

I haven't tested the basic library but this should works. You may have to debounce the onScroll method to avoid spam the event emitter.

Hope it will helps you.