Tips for executing a function when nearing the bottom of a scroll:

I have incorporated the angular2-infinite-scroll plugin, specifically version 0.1.4.

You can view my plunker here.

Currently, the function onScrollDown() only runs once at the beginning when scrolling.

I attempted to adjust the values for infiniteScrollDistance to both 2 and 0.8, but without success.

How can I ensure that onScrollDown() triggers only when nearing the bottom of the page?

@Component({
  selector: 'my-app',
  directives: [InfiniteScroll],
  styles: [`
    .search-results {
      height: 20rem;
      overflow: scroll;
    }
  `],
  template: `
    <div class="search-results"
         infinite-scroll
         [infiniteScrollDistance]="0.8"
         [immediateCheck]="true" 
         (scrolled)="onScrollDown()">
      <p *ngFor="let i of array">
        {{i}}
      </p>
    </div>
  `
})
export class App {
  array = [];
  sum = 20;

  constructor() {
    for (let i = 0; i < this.sum; ++i) {
      this.array.push(i);
    }
  }

  onScrollDown () {
    console.log('near the bottom!!');

    // add another 20 items
    const start = this.sum;
    this.sum += 20;
    for (let i = start; i < this.sum; ++i) {
      this.array.push(i);
    }
  }
}

Answer №1

If you want to track mouse movements and trigger events only when the mouse is close to the bottom of the page, you can create an observable for that purpose. Here's how you can do it:

const mouseMove$ = Observable.fromEvent(document, 'mousemove')
                      .filter(event => event.clientY > SOME_VALUE);

To calculate the value of SOME_VALUE dynamically based on the document height.

You can also create a second observable to track scroll events:

const scroll$ = Observable.fromEvent(document, "scroll");

After that, you can combine both observables to create a new one that emits values only when the mouse is moving at the bottom of the page and the user is scrolling:

const combined$ = Observable.combineLatest(
    mouseMove$, scroll$
);

Finally, you can subscribe to this combined observable to perform actions when the conditions are met:

combined$.subscribe(
    combined => {
       console.log("This is the mouse event", combined[0]);
       console.log("This is the scroll event", combined[1]);

       // Add your action here when the user is scrolling at the bottom of the page
    }
);

Answer №2

Implement an onScroll event listener to capture window scrolling in your code. Use a function like the example below and insert your custom functionality inside.

javascript

window.onscroll = function() {
    console.log("scrolling");
};

jQuery

$(window).on('scroll', function() {
    console.log("scrolling");
});

You can also utilize functions or methods that will provide you with the top and bottom positions of the window or viewport (depending on your requirements and whether you are using raw javascript, jQuery, or another framework). From there, you can perform calculations to trigger your desired functionality at the appropriate moment.

Answer №3

To resolve my issue, I had to modify the CSS from height: 20rem; to height: 100%;, and it worked like a charm. You can view the working plunker here.

In addition, @orizens included an official demo in the README.md file of angular2-infinite-scroll after my request.


If you prefer not to use angular2-infinite-scroll, @Angular University provides a helpful alternative using RxJS. Be sure to check out their answer for guidance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

The compilation of TypeScript extending DataType can sometimes result in errors

I have written a custom extension in my extensions/date.ts file which adds a method to the Date interface: interface Date { addDays: (days: number) => Date } Date.prototype.addDays = function(days: number): Date { if (!days) return this; let dat ...

Angular 6: Harnessing the Power of Subject

In my angular applications, I have been utilizing the Subject feature from the rxjs library to create an event emitter. However, upon migrating to Angular 6, I encountered the issue that this module is no longer available. Cannot find module 'rxjs/Su ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

The mat-paginator fails to display the page information

Material paginator is not displaying the page information correctly. In the official documentation, it shows the page info as 'Page 1 of 20', but when I run their code locally or on Stackblitz, the output is different. Instead, it shows the num ...

Customizing the HTMLElement class to modify particular attributes

Is there a way to modify the behavior of an HTMLElement's scrollTop property by adding some extra logic before updating the actual value? The common approach seems to be deleting the original property and using Object.defineProperty(): delete element. ...

Creating a Tailored Validation Function in Angular 6

Looking to develop a custom generic validator that accepts the regular expression pattern and the property name (from a formgroup) as parameters? Take a look at this code snippet: UserName: new FormControl('', [ Validators.require ...

Learn how to set up a class using TypeScript decorators

Is there a way to automatically initialize a class when a specific decorator is present above the class? For example: @apiController export class usersControllers extends lib.baseClasses.apiControllerBase().apiController { @lib.decorators.routesRegist ...

What is the correct method for storing a response in an array variable in Angular?

I am looking to save the response data from an API call in a variable and display it in the component.html file. Component.ts file : public coinsHistory = []; this.service.getCoinsHistory().subscribe( (response) => { this.handleCoinsRespon ...

Is it possible to enable tooltips to function through the innerHTML method?

Currently, I am utilizing the innerHTML attribute to modify the inner HTML of a tag. In this instance, it involves the <td></td> tag, but it could be applied to any tag: <td *matCellDef="let order" mat-cell [innerHTML]="order. ...

"Can you share a method to extract the value from a TextField component in a React hook-based Material-

Currently, I am using Material-UI within a React project and have a component set up like this: const UserDetail = (props: ListDetailProps) => { const oldpassword = useRef<TextFieldProps>(null); const newpassword = useRef<TextFieldProps ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

Unable to modify the date format in Ionic 2 once it has been initially selected by the user in the date

In this snippet of HTML, there are two elements - a button and a date input. <ion-datetime id="datetime-12-0" pickerFormat="DD/MMM/YY" min="2017" max="2020" [(ngModel)]="date.date"></ion-datetime> <button (click)="triggerClick('dat ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

Unable to define the type for the style root in Typescript

I am encountering an error that is asking me to code the following types in the root tag: No overload matches this call. Overload 1 of 2, '(style: Styles<Theme, {}, "root">, options?: Pick<WithStylesOptions<Theme>, "fli ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

What is the significance of including parameter names in Typescript function type signatures?

Just diving into typescript for the first time, so bear with me... I decided to create a simple filter function for a container I had created class Container<T> { filter(predicate: (T) => boolean): Container<T> { for(const elem ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Troubleshooting Observable data in Angular 2/Typescript - A Comprehensive Guide

After going through the Angular 2 tutorial, I managed to create a search feature that asynchronously displays a list of heroes. <div *ngFor="let hero of heroes | async"> {{hero.name}} </div> In my component, I have an observable array of ...