1 import { Directive, EventEmitter, Input, OnInit, Output } from '@angular/core'
2 import 'rxjs/add/operator/debounceTime'
3 import 'rxjs/add/operator/distinct'
4 import 'rxjs/add/operator/distinctUntilChanged'
5 import 'rxjs/add/operator/filter'
6 import 'rxjs/add/operator/map'
7 import 'rxjs/add/operator/startWith'
8 import 'rxjs/add/operator/throttleTime'
9 import { fromEvent } from 'rxjs/observable/fromEvent'
12 selector: '[myInfiniteScroller]'
14 export class InfiniteScrollerDirective implements OnInit {
15 private static PAGE_VIEW_TOP_MARGIN = 500
17 @Input() containerHeight: number
18 @Input() pageHeight: number
19 @Input() percentLimit = 70
20 @Input() autoLoading = false
22 @Output() nearOfBottom = new EventEmitter<void>()
23 @Output() nearOfTop = new EventEmitter<void>()
24 @Output() pageChanged = new EventEmitter<number>()
26 private decimalLimit = 0
27 private lastCurrentBottom = -1
28 private lastCurrentTop = 0
31 this.decimalLimit = this.percentLimit / 100
35 if (this.autoLoading === true) return this.initialize()
39 const scrollObservable = fromEvent(window, 'scroll')
42 .map(() => ({ current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }))
46 // Check we scroll down
47 .filter(({ current }) => {
48 const res = this.lastCurrentBottom < current
50 this.lastCurrentBottom = current
53 .filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
55 .subscribe(() => this.nearOfBottom.emit())
60 .filter(({ current }) => {
61 const res = this.lastCurrentTop > current
63 this.lastCurrentTop = current
66 .filter(({ current, maximumScroll }) => {
67 return current !== 0 && (1 - (current / maximumScroll)) > this.decimalLimit
70 .subscribe(() => this.nearOfTop.emit())
75 .map(({ current }) => Math.max(1, Math.round((current + InfiniteScrollerDirective.PAGE_VIEW_TOP_MARGIN) / this.pageHeight)))
76 .distinctUntilChanged()
77 .subscribe(res => this.pageChanged.emit(res))