Angular中使用Intersection Observer API实现无限滚动效果
背景:
实现原理为 在data下面加一个loading元素 如果此元素进入视窗 则调用api获取新的数据加到原来的数据里面,这时loading就会被新数据顶下去,如此循环。
<div id="dataContainer"></div> <div id="loadingContainer"></div>
传统angular实现是使用ngAfterViewInit()生命周期,写在指令(Directive)里面,并且传出一个事件,触发时回调被监控组件里面的具体函数。
不过对于异步操作,元素可能在ngAfterViewInit被调用时还没有完成初始化而导致bug,所以用ngAfterViewChecked() 会更稳,当然也更会导致性能问题,每次变更检测它都被调用,这可能会增加应用程序的负载。
所以这里使用h5 提供的新API ——交叉观察器 API(Intersection Observer API)提供了一种异步检测目标元素与祖先元素或顶级文档的视口相交情况变化的方法。
效果如图,为了截到loading,我在增加数据的函数里面加了个等待。
上代码
watch-to-view.directive.ts
import { Directive, Output,EventEmitter, ElementRef } from '@angular/core'; @Directive({ selector: '[appWatchToView]' }) export class WatchToViewDirective { private observer:IntersectionObserver; @Output() appWatchToView = new EventEmitter<IntersectionObserverEntry>(); constructor(public el:ElementRef) { this.observer = new IntersectionObserver(this.callback,{rootMargin:'100px',threshold:1,root:null}); this.observer.observe(el.nativeElement); } public callback = (entries: IntersectionObserverEntry[]) => { entries.forEach((entry: IntersectionObserverEntry) => { if (entry.isIntersecting) { this.appWatchToView.emit(entry); } }) } }
app.component.html
<div id="dataContainer"> <ul> <li class="blueBox" *ngFor="let i of data">{{i}}</li> </ul> </div> <div id="loadingContainer" class="blueBox" appWatchToView (appWatchToView)="this.loadObserver($event)">Loading more...</div>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Tour of Herors'; batch:Number = 10; len:Number = this.batch; data:Array<Number>=new Array(this.batch).fill(0).map((_,i)=>i); loadObserver = async function (event){ console.log(event.target); await new Promise(resolve => setTimeout(resolve, 1000)); this.data.push(...new Array(this.batch).fill(0).map((_,i)=>i+this.len)); this.len+=this.batch; } }
再给个样式吧
.blueBox{ display: block; width: 100%; height: 100px; background-color: #38b1ee; margin-top: 5px; text-align: center; color: white; font-size: large; }
官方link: https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API
到此这篇关于Angular中使用Intersection Observer API实现无限滚动的文章就介绍到这了,更多相关Angular无限滚动内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
AngularJS中ng-options实现下拉列表的数据绑定方法
今天小编就为大家分享一篇AngularJS中ng-options实现下拉列表的数据绑定方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-08-08详解使用angular-cli发布i18n多国语言Angular应用
这篇文章主要介绍了详解使用angular-cli发布i18n多国语言Angular应用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05Angular 4依赖注入学习教程之ClassProvider的使用(三)
这篇文章主要给大家介绍了关于Angular 4依赖注入之ClassProvider使用的相关资料,文中介绍的非常详细,对大家学习或者使用Angular 4具有一定的参考学习价值,需要的朋友可以参考借鉴,下面来一起看看吧。2017-06-06AngularJS中如何使用$http对MongoLab数据表进行增删改查
这篇文章主要介绍了AngularJS中如何使用$http对MongoLab数据表进行增删改查的相关资料,需要的朋友可以参考下2016-01-01
最新评论