it编程 > 前端脚本 > AngularJs

Angular中使用Intersection Observer API实现无限滚动效果

59人参与 2024-06-01 AngularJs

背景:

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

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Angular依赖注入系统里Injection token PLATFORM_ID使用场景详解

06-01

Angular Universal服务器端渲染避免 window is not defined错误消息

06-01

如何处理Angular 错误消息ERROR Error NullInjectorError No provider for XX

06-01

angular报错can't resolve all parameters for []的解决

06-01

基于 angular material theming 机制修改 mat-toolbar 的背景色(示例详解)

06-01

AngularJS 的生命周期和基础语法使用详解

05-26

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论