Angular's p-tree nodes can be loaded on scroll for enhanced user experience

I have a large dataset that needs to be displayed on a page, and I'm attempting to implement an infinite scroll feature to load more data as the user scrolls down. However, I'm encountering issues with debugging my directive. Can someone assist me in triggering the scroll event when reaching the bottom? Is there another method to capture the scroll event on a div element so that I can enhance the performance of my webpage?

explore.component.html

<div style="overflow: auto !important;height: 488px !important;" scrollTracker (scrollingFinished)="onScrollingFinished()">
<p-tree [value]="files | filter:searchText" selectionMode="single" [(selection)]="selectedFiles"
(onNodeSelect)="nodeSelect($event)" (onNodeExpand)="expandNode($event)" ></p-tree>
</div>

explore.component.ts:

@Output() scrollingFinished = new EventEmitter<void>();
 

onScrollingFinished() {
this.scrollingFinished.emit();
}

directive:

import { Directive, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({
selector: '[scrollTracker]'
})
export class ScrollTrackerDirective {
@Output() scrollingFinished = new EventEmitter<void>();

emitted = false;

@HostListener("window:scroll", [])
onScroll(): void {
debugger;
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight && !this.emitted) {
this.emitted = true;
this.scrollingFinished.emit();
} else if ((window.innerHeight + window.scrollY) < document.body.offsetHeight) {
this.emitted = false;
}
}
}

Answer №1

Always make sure to listen for the scroll event on the actual element where it is being triggered.

In this scenario, you should be listening for the scroll event on the scrollable div within your template, which is the element that has the scrollTracker directive applied to it.

To achieve this, you need to replace window:scroll with the scroll event specifically on the target element, which in this case is the scrollable div. Within your onScroll method:

constructor(private element: ElementRef) {}

@HostListener('scroll', ['$event'])
public onScroll(event) {
    let element = this.element.nativeElement;
    if (element.scrollTop + element.clientHeight + 50 > element.scrollHeight) {
        // reached the bottom 
    }
}

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

Tips for populating all the ionic form fields using speech recognition technology

In the process of developing an Ionic 4 application, I am faced with a challenge where I need to fill in multiple form fields using the Ionic speech-recognition plugin. Currently, I am only able to populate one field at a time. What I am looking for is a w ...

Building Interface/Type with Static Properties and Constructor Signature in TypeScript

I am looking to devise an interface or a type that contains static properties and a constructor signature. My goal is to utilize this interface/type as a parameter for a function. I experimented with using an interface, but encountered limitations in decla ...

Highlighting the selected value in an Angular Material mat option

I am looking to enhance the background color of the selected value when it is clicked. Unlike the example I found, which highlights multiple select values, I only want to highlight the selected value when choosing an option. Check out this example for ref ...

My React hooks are failing to properly update the state using useState

I have been encountering an issue with the code in my component where the state is not updating as expected. When I invoke the createUserList function, I can view the users in the UserList component. However, when I attempt to log the users in the UserCom ...

An observable value is intertwined with another observable

indexData and indexEditData serve as the observables within my application. The purpose of indexData is to store a json object that is used to populate a table. Editing of table rows is facilitated by selecting individual rows, triggering the transfer of t ...

What is the purpose of code indentation or adding semicolons in WebStorm?

In my Angular project, I am encountering a semicolon issue with arrow functions while using WebStorm. https://i.sstatic.net/R3Wmy.png By removing the semicolon, I was able to resolve the error. However, whenever I format my file using Command + Option + ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Issue with prop type: MUI - experiencing a warning while using ReactJS with MUI?

Upon attempting to open the datepicker by clicking on the icon, I encounter the following warning. Here is the code snippet where the error occurs: const DatePickerTextField = React.forwardRef((props: TextFieldProps, ref) => { const theme = useTheme() ...

What is the process for initiating a Fargate task once a database instance has been successfully provisioned using AWS CDK

I am currently working on an AWS CDK stack that involves creating a Fargate task (using ApplicationLoadBalancedFargateService) from a docker container. The container houses a web application that needs to connect to a database. Upon deploying the CDK stack ...

What steps can I take to enhance the quality of my PDF files? Currently, I am utilizing Jspdf in conjunction with html

My current challenge involves generating a PDF file from my application. Although I am able to create a PDF, the quality is not up to par. When I download the PDF, I notice some discrepancies in text quality. While it's not terrible, it's also n ...

Difficulty encountered when hosting an Angular and .Net Core application on a virtual machine's localhost

Having trouble running an application from a virtual machine on Azure? I'm facing an issue that I can't seem to solve. The application's front end is Angular and the backend is .NET Core 3.1. I'm using ngrok to tunnel my virtual machine ...

ng-mocks: NG0304: The component 'ng-mocks-ButtonComponent' is not recognized

While running test cases with Angular and ng-mocks, I encountered the following error: Error: NG0304 - 'ng-mocks-ButtonComponent' is not recognized as a valid element within the template. To resolve this error for an Angular component, ensure ...

Encountering issues when integrating an Angular library project into the main project

Currently, I am facing an issue with a library project (let's call it X) that contains 2 projects within it (X-core, X-core-members). My goal is to utilize this library in another angular project called ABC. I have made the necessary links in the tsco ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

Tips for retrieving a cropped image with Croppr.js

Currently, I am developing a mobile application using Ionic 3. Within the application, I have integrated the Croppr.js library to enable image cropping before uploading it to the server. However, I am facing an issue where I am unable to retrieve the cropp ...

Ignoring break lines in Javascript using regular expressionsKeeping break lines at bay with regular expressions

I need help modifying a regular expression to prevent users from inserting special characters like $ # ?. The current expression I am using is /^((?![#$%^*<>{}!=|/?])\s.)*$/ When I apply this expression on a textarea, Angular throws an error w ...

Determine if two arrays are equal using Jest

I have a method in the test.ts file: public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]> This method returns an array with data like this: [{ components: "toto", newVersion: "2", oldVersion: "1" }] I am attempting ...

Is the validator in my Angular reactive form malfunctioning?

I have been working on a service where I'm trying to validate the zip code field, but for some reason, the logic (result ? null : { IsInvalid: true }) is not executing. It makes me wonder if there's an issue with the reactive form or if I am usin ...

Is there a specific Angular signature pad that is capable of saving signatures as images?

I'm looking to create a signature pad for saving user signatures on my enterprise website. Can anyone recommend the best package for this task? ...

Jest unit tests in Angular using Typescript are not detecting failures when it comes to console errors or unrecognized elements

In my Angular Typescript project, I am facing an issue with my Jest unit test. The test does not fail even if a component (e.g., mat-paginator without importing MatPaginatorModule in configureTestingModule) or template bindings (e.g., [mask] directive from ...