Changing an event listener from using the `addEventListener` function to utilizing the fat arrow syntax. But the question remains: How do you access properties within the function's scope?

I am attempting to access the properties of an HTMLElement while working within the context of a fat arrow function. My objective is to determine when a user reaches the bottom of a virtualScroll element.

Although I have managed to successfully console log the end of the virtual scroll, I have encountered difficulties in storing this information in a variable that can be utilized by Typescript. Below is the code that currently works...

let virtualScroll = document.getElementById("virtualScroll") as HTMLElement;
virtualScroll.addEventListener('scroll', function(e){
  let x: boolean = false;
  if(this.scrollTop + this.clientHeight == this.scrollHeight){
    x = true;
  };
  console.log('virtualScroll END?: ', x);
  return(x);  // Unfortunately, even this cannot be used :<
})

However, my lack of understanding regarding the scope in fat arrow functions has hindered me from accessing "this.scrollTop" and other "this." properties.

virtualScroll.addEventListener('scroll', e => {
  console.log( Object.getPrototypeOf(e).scrollHeight );
})

The output from the second function consistently returns "undefined", indicating that there is an error in my implementation.

Answer №1

I may not have found the most elegant solution, but I managed to piece together something that gets the job done. Here's a setup that you'll need:

@Component({
  ...
  host: {
    '(window:resize)': 'onResize($event)',
  }
})

Variables...

@ViewChild(CdkVirtualScrollViewport)
viewport: CdkVirtualScrollViewport;
topOffset: number = 80;  // This refers to the CSS offset for my <app-bar>.

Initialization...

ngOnInit() {
  this.clientHeight = window.innerHeight - this.topOffset;
}

Handling Resize Event...

onResize(event){
  this.clientHeight = event.target.innerHeight - this.topOffset;
}

And now, the highlight of the script: determining the virtual scroll location!

virtualScrollLocation(){
      if(this.clientHeight + this.viewport.measureScrollOffset("top") == this.viewport.measureRenderedContentSize()){
        console.log("END")
      }
}

Answer №2

To make the transformation, you should change the function to an arrow function

The modification is a simple one

virtualScroll.addEventListener('scroll', (e) => {

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

Navigating with Angular 2 [routerLink] while including route parameters

Currently, I am working on developing an application using angular 2. As part of this project, I am trying to pass parameters to the [routerLink] tag in order to create a link structure like the following: <a href="/auth/signup?cell=1654654654">< ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

The union type cannot function effectively in a closed-off environment

Here is the code snippet I am working with: if (event.hasOwnProperty('body')) { Context.request = JSON.parse(event.body) as T; } else { Context.request = event; } The variable event is defined as follows: private static event: aws.IGateway ...

TypeScript class decorator for extending methods

I have been extensively researching decorators in TypeScript, but I have not been able to find comprehensive documentation that suits my specific needs. After exploring two possible solutions - AOP and Decorator, it seems like AOP is not fully functional ...

"Exploring the capabilities of Angular 4 Material for seamless page navigation

I am brand new to Angular 4 using Material Design 2. I have a simple inquiry regarding this topic. My code is in app.component.html, which displays a few mat-card components. When clicking on any link inside the mat-card component, it should switch the e ...

Typescript is outputting the error message: "cannot be assigned to the type 'IntrinsicAttributes & { children?: ReactNode; }'"

While there has been extensive discussion on this topic, I am unable to get any other solutions from SO to work, or I am struggling to implement them. I am completely new to TypeScript, and here is what I have: import faker from "faker"; import React fro ...

Transitioning from using the do() method in Angular 2 to tapping into the tap() method in Angular 6

I am currently working on implementing Server Side Pagination for a Grid using Angular 6 and Kendo Grid The code snippet I have is originally from Angular 2, sourced from the following link: public ngAfterViewInit(): void { this.grid.dataStateChange ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

Typescript typings for higher order components in React

I am currently attempting to incorporate an existing react component (react-select) within a High Order Component (HoC) to implement conditional rendering logic. The challenge lies in ensuring that TypeScript can properly integrate the properties of both t ...

Avoid generating file modifications due to a version update when using OpenApiGenerator

When utilizing the typescript-rxjs generator, the issue arises when generating a new version of API clients. The majority of files are altered due to a simple version change: * The version of the OpenAPI document: 1.47.0-rc.20. This results in real change ...

An error is being thrown in the Angular build due to an issue with parsing JSON after stripping out

Currently, I am working with angular nx alongside nestjs. Upon cloning the project and executing the yarn command, it successfully builds. However, whenever I try to install any package and compile the project, an error is thrown: **D:\projectNAme&bso ...

Steps to Implement ReadOnly FormControlTo create a formControl that is read

Is there a way to make a formControl in Angular read-only programmatically? I am aware that I can achieve this in HTML like so: <input type="text" formControlName="xyz" readonly /> But how can I do it from JavaScript code rather than HTML, in a mo ...

Can you please tell me the location of the sqlite database file in Ionic 2 Cordova?

Currently, I am working with cordova-plugin-sqlite within the context of angular2 ionic2. Interestingly, despite my efforts, I have not been able to locate the database file anywhere within my project structure. Numerous attempts to resolve this issue by ...

Utilizing CDK to transfer files to S3 storage bucket

I've been trying to upload a file to an S3 bucket created using CDK, but I keep encountering the same error even when using AWS's example code. Here is the stack: export class TestStack extends cdk.Stack { public readonly response: string; ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

What is the function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

What could be causing the issue with my React Native app's release version not opening on a physical Android device?

I encountered an issue while trying to install the Release version of my application. In order to test both the debug and release versions on my physical and virtual devices, I utilized the following commands: ./gradlew assembleDebug, ./gradlew assembleRel ...

Locate the minimum and maximum values between two inputted dates

I'm looking for a solution that provides strongly typed code. The problem arises when trying to implement solutions from a related question - Min/Max of dates in an array? - as it results in an error. TS2345: Argument of type 'Date' is not ...

Tips for showing an image through a button in Angular 4

Currently, I am in the process of creating a simple website and I have encountered an issue. When I click on a button to display an image, it works fine. However, when I click on another button to display a different image, the previous image remains visib ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...