当滚动位置到达底部时,如何在数组中推送项目?

时间:2018-07-11 01:26:34

标签: javascript angular

您能告诉我滚动位置到达底部时如何在数组中推送项目吗?我创建了一个directive,在其中添加了滚动事件。当用户将滚动条移动到bottom时,我想在数组中添加新项目。

这是我的代码: https://stackblitz.com/edit/angular-m1sgsm?file=src%2Fapp%2Fscroll.directive.ts

import { Directive,OnInit ,OnDestroy,NgZone} from '@angular/core';

@Directive({
  selector: '[appScroll]'
})
export class ScrollDirective implements OnInit ,OnDestroy{

  constructor(private ngZone: NgZone) { }

  ngOnInit() {
       this.ngZone.runOutsideAngular(() => {
            window.addEventListener('scroll', this.scroll, true);
        });//third parameter
    }

    ngOnDestroy() {
        window.removeEventListener('scroll', this.scroll, true);
    }

    scroll = (): void => {
      console.log('ddd')

    };

}

我从此链接获取帮助: How to handle window scroll event in Angular 4?

我们可以在scrolling之外运行angular代码,何时到达底部并在数组中添加一个项目,然后告诉angular

1 个答案:

答案 0 :(得分:0)

我想您可以update your scroll function检查目标的scrollTop值是否等于目标的scrollHeight - offsetHeight值。

  scroll = (e): void => {
    //e.target.scrollTop = current scroll position
    //e.target.scrollHeight - e.target.offsetHeight = to calculate the bottom. equivalent to scrollTopMax in FF
    if (e.target.scrollTop == e.target.scrollHeight - e.target.offsetHeight) {
      console.log('You reached the bottom!');
      //Push item into array
    }
  };

要将项目推入数组,请查看array.push方法的documentation