角度2向下滚动调用功能加载更多

时间:2017-10-24 14:34:26

标签: angular typescript

角度2 div高度为1000px我将滚动到达800px调用函数loadmore。

<div class="row" style="margin:0px 0px;height:1000px; overflow-Y:auto;">
   <div class="col-sm-3" *ngFor="let user of users ;let i = index ">
      <div class="user_main">
         <img *ngIf="user.image == ''"  src="http://localhost/AdminApp/assets/images/{{user.image}}"  class="user_img">
         <div style="margin:0px 5px;">
            <p class="user_name">{{user.first_name }} {{user.last_name}}</p>
            <p class="user_email"> {{user.email}} ,</p>
            <span class="user_job"> {{user.job}} </span>
         </div>
      </div>
   </div>
   <button (click)="LoadMore()"> Load More </button>
</div>

2 个答案:

答案 0 :(得分:2)

您可以为此创建一个指令,并使用@HostListener监听滚动事件:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[infiniteScroll]',
})
export class InfiniteScrollDirective {

  @Input() scrollThreshold = 200; // px

  constructor(private element: ElementRef) {}

  @Input('infiniteScroll') loadMore;

  @HostListener('scroll')
  public onScroll() {
    const scrolled = this.element.nativeElement.scrollTop;
    const height = this.element.nativeElement.offsetHeight;

    // if we have reached the threshold and we scroll down
    if (height - scrolled < this.scrollThreshold) {
      this.loadMore();
    }

  }

}

未经测试,但它应该让您朝着正确的方向前进。要使用它,请这样做:

<div class="row"
     style="margin:0px 0px;height:1000px; overflow-Y:auto;"
     [infiniteScroll]="LoadMore">

您可能需要将LoadMore定义为箭头函数,以便保留上下文(this关键字)。

// in component controller
LoadMore = () => { // load more items };

答案 1 :(得分:1)

 @HostListener("window:scroll", ["$event"])
   onWindowScroll() {
   let pos = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.offsetHeight;
   let max = document.documentElement.scrollHeight;
   if(pos == max )   {
       // action here
          }
   }