Encountering an issue when attempting to attach an event listener to the entire document

I need help troubleshooting an issue with a function that is supposed to perform certain operations when the scrollbar is moved. I attached an event listener to the document using an ID, but it's resulting in an error.

ERROR Message: TypeError: Cannot read property 'nativeElement' of undefined


ngOnInit() {
    document.getElementById('sidenav').addEventListener('scroll', () => this.onScroll('$event'), true);  
  }

  ngOnChanges(changes: SimpleChanges) {
    this.data = changes.data.currentValue;
    this.data_display = changes.data.currentValue.slice(0, 6);
  }

  ngOnDestroy() {
    console.log('destroy')
    document.getElementById('sidenav').removeEventListener('scroll', () => this.onScroll('$event'), false);
  }

  onScroll(event): void {
    const top = event.elementRef.nativeElement.scrollTop;
    const total = event.elementRef.nativeElement.scrollHeight;
    const height = event.elementRef.nativeElement.clientHeight;
    if ((height + top) === total) {
      if (this.data_display.length <= this.data.length) {
        this.data_display.push(...this.data.slice(this.start, this.end));
        this.start += 6;
        this.end += 6;
      }
      console.log('yes')
      this.cdr.detectChanges();
    }
  }

Answer №1

When working with Angular, it's important to note that you cannot directly add event listeners using the addEventListener method. However, a preferred way to do so is by utilizing @HostListener, as shown below:

@HostListener('window:scroll', ['$event'])
scrollEvent(event) { 
    // Statements
 }

Alternatively, you can also add event listeners like this, but keep in mind that the callback may not be removed when the component is destroyed:

window.addEventListener("scroll", this.onScroll, true);

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

Location of images in Tomcat for an Angular 7 application

I'm facing an issue with image source paths while working on my local Windows machine (Windows 10, Visual Studio Code 1.30.2) and deploying to Tomcat 9 on an Ubuntu 18.04 server hosted on AWS. When I build on Windows using Powershell: ng build --prod ...

The addition operator is not compatible with the given types

Hello, I am currently working on integrating PayPal into an Angular 5 project. The code snippet below shows how I render PayPal buttons using a function: ngAfterViewChecked(): void { if (!this.addScript) { this.addPaypalScript().then(() => { ...

Is there a way to retrieve the resolved data within the route definition in Angular?

I am looking to execute some actions within the route definition once the lazyloaded module is loaded. The route includes a resolver called UserDataResolverService. How can I retrieve and utilize the resolved data within the route definition? { ...

Limit the field type depending on the value of another field

Consider the following scenario: type ActionType = 'action1' | 'action2' | 'action3'; interface Action { type: ActionType; value?: number | Date; } Is there a method in typescript to enforce restriction ...

Typescript is unable to access the global variables of Node.js

After using Typescript 1.8 with typings, I made the decision to upgrade to typescript 2.8 with @types. When I downloaded @types/node, my console started showing errors: error TS2304: Cannot find name 'require'. The project structure is as foll ...

Tips for obtaining type narrowing for a function within a mixed array

In my coding adventure, I have crafted a brilliant match function. This function is designed to take a value along with an array of [case, func] pairs. The value is then compared to each case, and if a match is found, the associated func is executed with t ...

Can you explain the TypeScript type for the queryKey in React Query?

Currently utilizing react query in conjunction with typescript. What should be the type of arguments passed to the function? export const useIsTokenValid = () => { const { data: token } = useQuery<string | null>(['token'], getToken, { r ...

Creating a function within a module that takes in a relative file path in NodeJs

Currently, I am working on creating a function similar to NodeJS require. With this function, you can call require("./your-file") and the file ./your-file will be understood as a sibling of the calling module, eliminating the need to specify the full path. ...

Exploring ways to exclude a column in a TypeORM entity while also providing the flexibility to make it optional for retrieval using the Find method

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; } i prefer not to include the password here as I want it to be returned to the client: ...

Comparison between Destructuring in TypeScript and JavaScript

Starting my journey with TypeScript after a background in JavaScript. In the realm of modern JavaScript, one can easily destructure objects like this: let {n,s} = {n:42, s:'test'}; console.log(n, s); // 42 test Assuming TypeScript follows su ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

It appears that the functions in linqts are not clearly defined

Currently, I am in the process of learning Angular4 and facing challenges with getting linqts to function properly. Within my room-list.component.ts file, I include it in this manner: import { List } from 'linqts'; A few lines below, I have my ...

Adjust Column Title in Table

Is it possible to customize the column headers in a mat-table and save the updated value in a variable? I've been looking for a solution to this but haven't found one yet. ...

Using `querySelector` in TypeScript with Vue 3

Encountered a TypeScript error while using the Vue Composition API let myElement = document.querySelectorAll('my-element') The TS error I'm getting when trying to access it like this: Property '_props' does not exist on type ...

Encountering Angular error when trying to assign an undefined array to another array while using mock data

Attempting to conduct unit testing on a component involving the retrieval of 'Groups' data through a data resolver class. Below is the corresponding code: export class GroupsComponent implements OnInit, OnDestroy { group: IGroup; groups: IGro ...

Display a picture retrieved from a POST request using Angular and a Spring Boot backend

Recently, I've been delving into the world of HTTP requests. My latest task involves uploading an image from the client and sending it to the server using a POST request. When testing this process in Postman, everything works smoothly as I receive th ...

Ways to receive real-time notifications upon any modifications in my cloud firestore database?

I am currently in the process of developing a chat application using Angular and Firebase Cloud Firestore. My goal is to have a counter on the client side that updates whenever any document in the 'groups' collection is updated. Within my clien ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

Today is a day for coming together, not for waiting long periods of

When grouping by month and dealing with different days, I encountered an issue similar to the one shown in this image. https://i.stack.imgur.com/HwwC5.png This is a snapshot of my demo code available on stackblitz app.component.html <div *ngFor="let ...

React: Updating a property in an array of objects causes properties to become undefined

My intention was simply to update a property within an object inside an array and then update the state of the array. However, I encountered an issue where all properties except the one that was updated became undefined. The code in question is as follows ...