The intended 'this' keyword is unfortunately replaced by an incorrect '

Whenever the this keywords are used inside the onScroll function, they seem to represent the wrong context. Inside the function, it refers to the window, which is understandable. I was attempting to use the => arrow notation to maintain the correct reference to this, but I couldn't find the right syntax or placement for it in this situation.

Even storing this in a public self = this variable didn't work for some reason. However, I would prefer a solution that utilizes the => notation.

Below is the structure of the class:

export class ScrollXDirective implements AfterContentInit {
  @ContentChild(FormDatepickerPresetsComponent) presets: FormDatepickerPresetsComponent;

  public posX: number = 0;
  public offset: number = 35;

  constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

  ngAfterContentInit() {

    let wrapper: HTMLElement = this.presets.presetsWrapperElement.nativeElement;
    let scrollHandler: string = 'DOMMouseScroll' in window ? 'DOMMouseScroll' : 'mousewheel';   

    this._renderer.listen(wrapper, scrollHandler, _.debounce(this.onScroll, 200));
  }

  onScroll(e: any) {

    e.preventDefault();

    let delta = (e.type === 'DOMMouseScroll' ? e.detail * -40 : e.wheelDelta);

    let list: HTMLElement = this.presets.presetsListElement.nativeElement;
    let totalWidth = list.offsetWidth;

    if (delta > 0) {

      if (this.posX >= 0) {
        return false;
      }

      this.posX = this.posX + this.offset;

      this._renderer.setElementStyle(list, 'margin-left', this.posX + 'px');
    }
    else {

      let listX = list.getBoundingClientRect().right;
      let hostX = this._elementRef.nativeElement.getBoundingClientRect().right;

      if (listX <= hostX) {
        return false;
      }

      this.posX = this.posX - this.offset;

      this._renderer.setElementStyle(list, 'margin-left', this.posX + 'px');
    }
  }
}

Answer №1

My suggestion for making it work is:

 _.throttle(this.onScroll.bind(this), 200)

To learn more, check out the bind documentation

Alternatively, you can try this approach:

onScroll = (e: any) => {
  ...
}

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

Don't forget to retain the checkboxes that were chosen in the

I am looking for a solution to a specific scenario. When I open a modal box and check some checkboxes, I want those same checkboxes to be selected the next time I open it. Below is an example of my code. Main Controller modal function function openModa ...

React app experiencing freezing due to custom asynchronous function utilisation

I am currently facing an issue with my personal project where the application freezes under certain circumstances. The initial load works fine, but when I make changes to the code causing React to re-render, the app just freezes. It seems to be related to ...

Steps for creating a jQuery function that responds to changes in a text box value

Currently, I have a text box containing certain values and a submit button alongside a slider. When I click the submit button, the slider changes. However, I would like to achieve the functionality where instead of clicking the submit button, changing the ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Encountering a problem with Typescript and eslint while utilizing styled-components and Material UI: "Warning: React does not identify the `showText` prop on a DOM element."

While using a styled component to return a material ui Fab component, an error appears in the console: React does not recognize the `showText` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as low ...

Encountering an issue with Angular where all parameters for NgZone cannot be resolved

Currently, I am in the process of learning Angular and experimenting with the Firebase Authentication services. However, every time I try to load the component that utilizes this service, I encounter an error. Error: Can't resolve all parameters for N ...

What is the best way to create a map in React that allows for changing the state without affecting all elements?

When working with a JSON file containing various values, one of them being "iframe" which can hold either "si" (yes) or "no" based on whether it should include an iframe. With this value (yes/no), I need (this.props.tabsiframe === 'yes') to deter ...

Can a variable be declared within the path references of the Firebase database?

In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Fire ...

Sign up for an observable within an observable

Imagine a scenario where there is a function in a provider: saveCar(car: Car) { return this.saveCarImages(car).subscribe( (data:any) => { if(data[0].seats){ car=data[0]; } return this.api.put(`/car/${car.id}`, ca ...

How can I ensure that the HTML I retrieve with $http in Angular is displayed as actual HTML and not just plain text?

I've been struggling with this issue for quite some time. Essentially, I am using a $http.post method in Angular to send an email address and message to post.php. The post.php script then outputs text based on the result of the mail() function. Howev ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

What are some ways to adjust the page being served in node.js?

I have set up my server.js file with necessary dependencies and routing for handling POST requests. However, I am looking to dynamically update the webpage served by this server when a POST request is received on /message endpoint. These requests are trigg ...

Utilizing Angular 2 for Integration of Google Calendar API

I recently attempted to integrate the Google Calendar API with Angular 2 in order to display upcoming events on a web application I am developing. Following the Google Calendar JavaScript quick-start tutorial, I successfully managed to set up the API, inse ...

Passing a parameter to an AngularJS directive, which triggers the opening of an ngDialog, and subsequently updating the value to reflect changes in the root scope

Struggling with a persistent issue here; Essentially, I have a directive that triggers an ngDialog to open. This directive should be able to receive a variable from the root scope. The directive contains a click event that opens an ngDialog which then use ...

Exploring the world of ng2-translate for translating texts

For the translation of headings and texts in my Angular2 web application, I utilized ng2-translate. However, I am facing a dilemma when it comes to translating texts that are passed from a .ts file. For example, I can easily translate texts in an HTML fi ...

Changing the color gradient of a range column chart in ApexCharts

Currently, I am working on a project where I am trying to incorporate a waterfall chart using ApexCharts. Unfortunately, the Waterfall chart is not readily available with ApexCharts, so I am experimenting with modifying the range column chart into a Waterf ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...

Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers. However, I've ...

Encountering an error when accessing dynamically routed pages in Next JS

When I click on a link within the web app to navigate to a dynamically routed page for a product (http://localhost/1), everything works as intended. However, if I manually input a specific product number in the search bar to navigate directly to that page ...

Tips for optimizing the "framerate" (setInterval delay) in a JavaScript animation loop

When creating a JavaScript animation, it's common practice to use setInterval (or multiple setTimeouts) to create a loop. But what is the optimal delay to set in these setInterval/setTimeout calls? In the jQuery API page for the .animate() function, ...