Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular scroll directive for element support for infinite scroll
<div class="parent">
<div class="head">
Title
</div>
<div class="body" appScroll [offsetHeight]="200" (onBottomRached)="onBottomReached($event)">
<div class="content" *ngFor="let i of loop; let j = index">item - {{j+1}}</div>
</div>
</div>
.parent {
width: 100%;
height: 100vh;
.head {
height: 200px;
background-color: red;
}
.body {
height: calc(100% - 200px);
background-color: yellow;
overflow: auto;
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
loop = new Array(500);
onBottomReached(scrolled: number) {
this.loop = this.loop.concat(this.loop, new Array(500));
}
}
import { Directive, ElementRef, AfterViewInit, Input, OnDestroy, Output, EventEmitter } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Directive({
selector: '[appScroll]'
})
export class ScrolllDirective implements AfterViewInit, OnDestroy {
@Input() offsetHeight: number;
@Output() onBottomRached = new EventEmitter<number>();
scrolled = 0;
scrollSub: Subscription;
ngAfterViewInit(): void {
const el = (this.el.nativeElement as HTMLElement);
fromEvent(el, 'scroll', {passive: true}).pipe(debounceTime(500)).subscribe(() => {
const scrolled = (el as HTMLDivElement).scrollTop;
const scrolledOffsetHeight = (el.scrollHeight - el.clientHeight);
if(((scrolledOffsetHeight - scrolled) < 200) && (this.scrolled < scrolled)) {
this.onBottomRached.next(scrolled);
}
this.scrolled = scrolled;
})
}
constructor(private el: ElementRef) { }
ngOnDestroy(): void {
if(this.scrollSub) {this.scrollSub.unsubscribe}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment