1 import { Directive, EventEmitter, Input, OnInit, Output } from '@angular/core'
2 import 'rxjs/add/operator/distinct'
3 import 'rxjs/add/operator/startWith'
4 import { fromEvent } from 'rxjs/observable/fromEvent'
7 selector: '[myInfiniteScroller]'
9 export class InfiniteScrollerDirective implements OnInit {
10 private static PAGE_VIEW_TOP_MARGIN = 500
12 @Input() containerHeight: number
13 @Input() pageHeight: number
14 @Input() percentLimit = 70
15 @Input() autoLoading = false
17 @Output() nearOfBottom = new EventEmitter<void>()
18 @Output() nearOfTop = new EventEmitter<void>()
19 @Output() pageChanged = new EventEmitter<number>()
21 private decimalLimit = 0
22 private lastCurrentBottom = -1
23 private lastCurrentTop = 0
26 this.decimalLimit = this.percentLimit / 100
30 if (this.autoLoading === true) return this.initialize()
34 const scrollObservable = fromEvent(window, 'scroll')
36 .map(() => ({ current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }))
40 // Check we scroll down
41 .filter(({ current }) => {
42 const res = this.lastCurrentBottom < current
44 this.lastCurrentBottom = current
47 .filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
50 .subscribe(() => this.nearOfBottom.emit())
55 .filter(({ current }) => {
56 const res = this.lastCurrentTop > current
58 this.lastCurrentTop = current
61 .filter(({ current, maximumScroll }) => {
62 return current !== 0 && (1 - (current / maximumScroll)) > this.decimalLimit
66 .subscribe(() => this.nearOfTop.emit())
72 .map(({ current }) => Math.max(1, Math.round((current + InfiniteScrollerDirective.PAGE_VIEW_TOP_MARGIN) / this.pageHeight)))
73 .distinctUntilChanged()
74 .subscribe(res => this.pageChanged.emit(res))