angular9教程之PullToRefresh

Fork Me On Github

使用

html
            
<app-pull-to-refresh class="items-box" (refreshChange)="tapRefresh()" (moreChange)="tapMore()" [more]="hasMore" [loading]="isLoading">
    <ng-container *ngFor="let item of items">
        <dl class="book-item" (click)="tapItem(item)">
            <dt>
                <a >{{ item.title }}</a>
                <span class="book-time">{{ item.created_at }}</span></dt>
                <dd>
                    <p>{{ item.description }}</p></span>
            </dd>
        </dl>
    </ng-container>
</app-pull-to-refresh>
123456789101112

refreshChange 下拉刷新事件

moreChange 加载更多事件

more 是否有更多

loading 是否加载中

distance 触底距离

ts
                                 
  @ViewChild(PullToRefreshComponent)
  public pullBox: PullToRefreshComponent;

    public tapRefresh() {
    this.goPage(1);
  }

  public tapMore() {
    if (!this.hasMore) {
        return;
    }
    this.goPage(this.page + 1);
  }

  public goPage(page: number) {
    if (this.isLoading) {
        return;
    }
    this.isLoading = true;
    this.pullBox?.startLoad();
    this.service.getPage({
      page
    }).subscribe(res => {
      this.page = page;
      this.hasMore = res.paging.more;
      this.isLoading = false;
      this.items = page < 2 ? res.data : [].concat(this.items, res.data);
      this.pullBox?.endLoad();
    }, () => {
      this.isLoading = false;
      this.pullBox?.endLoad();
    });
  }
123456789101112131415161718192021222324252627282930313233

推荐使用方法通知,虽然 loading 也可以,但是如果加载没有时间间隔的话,是不起作用的。

startLoad 指定开始加载

endLoad 指定加载完成

监听滚动事件

ts
                
@HostListener('scroll', [
    '$event.target.scrollTop',
    '$event.target.scrollHeight',
    '$event.target.offsetHeight',
  ])
  public onDivScroll(
    scrollY: number,
    scrollheight: number,
    offsetHeight: number,
  ): void {
    const height = scrollheight;
    const y = scrollY + offsetHeight;
    if (this.more && y + this.distance > height) {
      // 触发加载更多
    }
  }
12345678910111213141516

缺点

第一次不能自动加载,如果有更多,但没有滚动条,也不会自动加载更多

具体代码

请查看【GITHUB

点击查看全文
标签: angular
0 425 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式