Angular Detect When Scroll Reached Certain Point

How to detect scroll to bottom of html element

I think that all you want to do is detect the position of scroll.

@HostListener("window:scroll", ["$event"])
onWindowScroll() {
//In chrome and some browser scroll is given to body tag
let pos = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.offsetHeight;
let max = document.documentElement.scrollHeight;
// pos/max will give you the distance between scroll bottom and and bottom of screen in percentage.
if(pos == max ) {
//Do your action here
}
}

Also don't forget to import HostListener from @angular/core.

Detect bottom scroll

You can use the ionScroll events here

since there is no scrollBottom (which is a counterpart for `scrollTop), you need to get it yourself. So here:

In your .html, add (ionScroll) to handle any scroll events

<ion-content (ionScroll)="detectBottom()">
....
</ion-content>

And in your .ts

//make sure you import the correct modules
@ViewChild(Content) content: Content;
...
detectBottom(){
if(this.content.scrollTop == this.content.scrollHeight - this.content.contentHeight){
console.log("bottom was reached!");
}
}

Scroll events happen outside of Angular's Zones. This is for
performance reasons. So if you're trying to bind a value to any scroll
event, it will need to be wrapped in a zone.run()

Please refer to this example on stackblitz

Check if user has scrolled to the bottom in Angular 2

// You can use this.

@HostListener("window:scroll", [])
onScroll(): void {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
}

Tracking scroll position and notifying other components about it

I think the easiest way is each interested component listening to the scroll event.

  @Component({
...
// alternative to `@HostListener(...)`
// host: {'(window:scroll)': 'doSomething($event)'}
})
class SomeComponent {
@HostListener('window:scroll', ['$event'])
doSomething(event) {
// console.debug("Scroll Event", document.body.scrollTop);
// see András Szepesházi's comment below
console.debug("Scroll Event", window.pageYOffset );
}
}

plunker

Plunker using @HostListener()

Hint:

bootstrap(MyComponent, [
provide(PLATFORM_DIRECTIVES, {useValue: [TrackScrollDirective], multi:true})]);

makes the directive universal without adding it to every components directive: [...] list.

How to detect scroll reached end in ion-content component of Ionic 4?

These features are still available they are just in a different location.

After enabling it with scrollEvents, you need to use the ionScroll event and then calculate the height based on the results of the getScrollElement() function, not the ion-content - that has a fixed height of the window height.

I've written an example below. You can remove the console.log's and tighten it up a bit, I just left them in to help you understand what's going on.

Example page:

<ion-header>
<ion-toolbar>
<ion-title>detectScrollToBottom</ion-title>
</ion-toolbar>
</ion-header>

<ion-content [scrollEvents]="true" (ionScroll)="logScrolling($event)">
<p *ngFor="let dummy of ' '.repeat(75).split('')">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia placeat nam sapiente iusto eligendi</p>
</ion-content>

Example code:

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-detect-scroll-to-bottom',
templateUrl: './detect-scroll-to-bottom.page.html',
styleUrls: ['./detect-scroll-to-bottom.page.scss'],
})
export class DetectScrollToBottomPage implements OnInit {

private scrollDepthTriggered = false;

constructor() { }

ngOnInit() {
}

async logScrolling($event) {
// only send the event once
if(this.scrollDepthTriggered) {
return;
}

console.log($event);

if($event.target.localName != "ion-content") {
// not sure if this is required, just playing it safe
return;
}

const scrollElement = await $event.target.getScrollElement();
console.log({scrollElement});

// minus clientHeight because trigger is scrollTop
// otherwise you hit the bottom of the page before
// the top screen can get to 80% total document height
const scrollHeight = scrollElement.scrollHeight - scrollElement.clientHeight;
console.log({scrollHeight});

const currentScrollDepth = scrollElement.scrollTop;
console.log({currentScrollDepth});

const targetPercent = 80;

let triggerDepth = ((scrollHeight / 100) * targetPercent);
console.log({triggerDepth});

if(currentScrollDepth > triggerDepth) {
console.log(`Scrolled to ${targetPercent}%`);
// this ensures that the event only triggers once
this.scrollDepthTriggered = true;
// do your analytics tracking here
}
}

}

Example logs:

example log output

Detect scroll event on element.nativeElement angular

The actual scroll code is fine. The reason it's not working in the Angular 8 version is that you're scrolling on the page, not on the div. The difference between the two is that the working example has a fixed height with overflow: scroll whereas the non-working example has the div taking up its entire height.

To get it to work, you can simply add the following css to the .scrolling-guy div:

height: 500px;
overflow-y: scroll;

Working example



Related Topics



Leave a reply



Submit