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

Showing identification and name within a URL path - Angular

I am looking to update a URL path within a website from http://localhost:4200/viewbrand/1 to http://localhost:4200/viewbrand/1/soap, where "soap" is added after the ID in the path. The current code in the routing module.ts file is as follows: { path: &apo ...

Troubleshooting Issue: Ionic 3 and Angular ngForm not transmitting data

Attempting to create a basic crud app with ionic 3, I am encountering an issue where new data cannot be inserted into the database. The problem seems to lie in the PHP server receiving an empty post array. Below is my Ionic/Angular code: Insert.html < ...

The function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

Challenging Issue: "The 'any' type cannot be assigned to the 'never' type"

Currently facing a challenging Typescript problem that has me puzzled. The issue arises at the line themeToChange[tileId][key] = value; The error message states Type 'any' is not assignable to type 'never' This error is directly rela ...

Preflight request response failed access control check due to absence of 'Access-Control-Allow-Origin' header

I encountered an error while attempting to upload a file and store it in a database using Angular4 as the front end. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

When attempting to navigate to a sub-route, I am encountering the error message: "Unable to find a matching route" in Angular 6

The initial code is functional, but not the best practice. const FooProcessingRoutes: Routes = [{ path: '', pathMatch: 'full', redirectTo: '/foo-processing/list', }, { path: 'list', component: FooListCompo ...

A guide on implementing directives in Angular 2

I am trying to load my navbar.html in my app.component.html by using directives and following the method below: Here is my navbar html: <p>Hi, I am a pen</p> This is my navbar.ts: import {Component, Directive, OnInit} from '@angular/c ...

The input element's value property updates only once

Whenever I input a number greater than 1 into the input field, the value automatically changes to 1 due to validation. Oddly enough, this only seems to work for the first number entered. For example, if I type in 11, the input value remains as it is instea ...

"Customizing text input colors in Angular Material: A step-by-step guide

Welcome to my User Form: https://i.stack.imgur.com/7eLp9.jpg I'm facing an issue where the color of the input field is white, blending with the background color. I've been searching for how to change the color of the input field without any luc ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

Error in angular2-color-picker module: Unable to retrieve the property 'substr' from an undefined source-node in source-node.js

Error in angular2-color-picker: Issue with 'substr' property, source-node.js This error occurred when I executed: npm i --save angular2-color-picker Any suggestions on how to fix this problem? ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

Ways to dynamically generate a generic that expands a union class type

Reviewing the code snippet: const events = { a: ['event1' as const, 'event2' as const], b: ['event3' as const, 'event4' as const], }; class SomeClass< T extends AnotherClass<typeof events[keyof typeof ev ...

Error in React Native Navigation: Passing parameters is not functioning properly

Within my React Native application, I have meticulously established the following routes in my app.js: export default class App extends Component { render() { return ( <NavigationContainer> <Stack.Navigator initialRouteName=&qu ...

Divide Angular ngFor into separate divs

Here is an example of my current array: [a, b, c, d, e, f, g, h, i] I am aiming to iterate through it using ngFor and split it into groups of 3 elements. The desired output should look like this: <div class="wrapper"> <div class="main"> ...

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...

This error message indicates that the certificate for Angular 13 has expired

After successfully installing Angular and verifying the version, I encountered an issue when attempting to run the command npm start. Despite multiple attempts at uninstalling and reinstalling everything, the problem persists. Running npm install also resu ...