¿Cómo activar un evento después de "desplazarse hacia abajo" en el dispositivo táctil? Tengo una lista de elementos donde cada vez que se desplaza >80% de la lista se cargan 10 elementos adicionales. El ejemplo a continuación funciona bien cuando uso el mouse y el teclado, pero cuando cambio al dispositivo táctil, no obtiene la altura superior de desplazamiento debido a que no se desplaza. ¿Cómo puedo lograr el mismo comportamiento en dispositivos móviles?
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 } }Dadas sus necesidades, adoptaría un enfoque totalmente diferente al suyo.
Aquí hay un ejemplo: https://stackblitz.com/edit/angular-ivy-ryetnx?file=src%2Fapp%2Fapp.component.ts
El principio es que el componente principal escucha los eventos de desplazamiento en sí mismo, detecta cuándo se ha alcanzado el límite y luego hace algo (como cargar más elementos).
Esta es solo la base, pero le brinda un enfoque ordenado para manejar sus necesidades.
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'); });