Angular 13 在一定高度后向上滑动触发事件

Angular 13 fire event on swiping up after certain height

如何在触摸设备上“向下滚动”后触发事件? 我有一个项目列表,每次滚动 >80% 的列表后都会加载 10 个额外的项目。 下面的示例在使用鼠标和键盘时工作正常,但当我切换到触摸设备时,由于它没有滚动,因此无法获得 scrollTop 高度。 我怎样才能在移动设备上实现相同的行为?

HTML

<div class="...">
  <angular-component
         id="article-list"
         (scroll)="onScroll('article-list')"
         [list]="list"
         class="...">
  </angular-component>
</div>

TS

@HostListener('touchstart', ['$event'])
onScroll(elementId: string): void {
  const articleList = document.getElementById(elementId);
   if (articleList) {
    const scrollPercent = Math.ceil((((articleList.offsetHeight + articleList.scrollTop) / 
     articleList.scrollHeight) * 100));
     if (scrollPercent < 30) {
       this.enableScrollToTopButton = false;
     } else {
       this.enableScrollToTopButton = true;
     }
      // code for loading items
   }
}

鉴于您的需求,我会采取与您完全不同的方法。

这是一个例子:https://stackblitz.com/edit/angular-ivy-ryetnx?file=src%2Fapp%2Fapp.component.ts

原理是父组件监听自己的scroll事件,检测到达到限制,然后做一些事情(比如加载更多元素)。

这只是基础,但它为您提供了一种巧妙的方法来处理您的需求。

  ngOnInit() {
    // Listen to the scroll of the host
    fromEvent(this.el.nativeElement, 'scroll')
      .pipe(
        // Throttle to trigger only if 50ms have elapsed
        throttleTime(50),
        map((event: any) => {
          const el: HTMLElement = event.target;
          const pageHeight = el.clientHeight;
          const totalHeight = el.scrollHeight;
          const currentScroll = el.scrollTop;

          // Get the bottom point of the page
          const bottomPoint = pageHeight + currentScroll;

          // Get the counts of page (if needed);
          const pageCount = Math.round(totalHeight / pageHeight);

          // Get the current scroll % of the user in the page
          const percentScroll = Math.round((bottomPoint * 100) / totalHeight);

          return { pageCount, percentScroll };
        }),
        // Check if more than 80% has been scrolled
        filter((v) => v.percentScroll >= 80),
        // Take only the first emission
        first()
      )
      .subscribe(() => {
        console.log('Page should load more items');
      });