背景:
实现原理为 在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无限滚动内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论