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

Generate various interactive charts

I am currently in the process of developing a web application using the MEAN stack. I am attempting to incorporate a ChartJS doughnut chart into my project, but I require it to be completely dynamic. Firstly, the number of charts needs to be dynamic as eac ...

How to incorporate a delay in ng-repeat using AngularJS

Currently, I am facing an issue with my ng-repeat block. In this block, I am generating elements based on data received from an ajax request, which sometimes causes a delay due to latency. Within the same block, I have implemented a filter to remove unwant ...

How can the session user object be modified after logging in?

I've encountered a strange issue and I'm puzzled about its origin. In my Next.js app, I make use of the next-auth library to implement the authentication system. Initially, everything seems fine - I can successfully sign in by verifying the cred ...

Adjust the width of Google chart to 100% automatically when the page is resized in Angular version 4 or higher

My application has numerous responsive wrappers on the site, each predefined from an API and containing a Google chart. The problem is that when the page initially loads, the charts are rendered at a specific size, and resizing the window only affects the ...

The RxJS mergeMap operator: The inner observable fails to execute

My goal is to upload multiple files, but before the upload can proceed, I need to send a POST request to get a personId. This personId will be used to link the uploaded files in the backend system. The postOnboardingRequestDto$ function successfully creat ...

Identify the parent container in jQuery and exclude any click events triggered by child input checkboxes

In my jQuery Mobile application, I have a piece of jQuery code that selects the child checkbox when a li is clicked. While this functionality works well, it interferes with the default behavior of the checkbox itself, making it impossible to deselect the c ...

The command 'create-react-app' is not valid and cannot be recognized as an internal or external command, operable program, or batch file

I've been struggling to set up a React project, as the create-react-app my-app command doesn't seem to be working. Can anyone offer some assistance? Here are the commands I'm using: npm install -g create-react-app create-react-app my-app ...

Angular throws an error when attempting to use localStorage as it is not defined in the environment

Encountering an issue while running this code, as the error message "localStorage is not defined" keeps popping up. Additionally, when it comes to todos != Todo[], why can't we simply set it to null instead of using the exclamation mark? import { Comp ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

Transmitting JSON information using post method through .ajax(), as well as receiving a JSON reply

Seeking assistance with debugging a registration page I am currently coding. I have hit a roadblock for the past 48 hours and would greatly appreciate any help in resolving the issues. CHALLENGE I am utilizing JavaScript to validate form inputs for error ...

Selection list with limited comment choices

I am facing a challenge and would greatly appreciate any hints. I am working with a PHP loop to populate comments for a thread, like this: <tr><td>'.comment_date'.</td><td>'.comment_author.'</td><td> ...

How can we manage JSON data in chunks during a progress event?

My dilemma involves dealing with a server request that may bring back a substantial JSON list (around 100K records, approximately 50 Mb) of points to be presented on a canvas using D3js. To ensure interactivity and save memory, I am keen on rendering them ...

Save the value of a promise in a variable for future use in state management within a React-Native application

let storage = AsyncStorage.getItem('@location_data').then(data => data) const MainApp = () => { let [currentLocation, setCurrentLocation] = useState(storage); The current situation is that the storage variable holds a promise. How can ...

Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this ...

Typedoc Error: Attempted to assign a value to an undefined option (mode)

After installing typedoc with the command npm install typedoc --save-dev, I proceeded to add typedocOptions to tsconfig.json: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", // ...some lin ...

PHP is unable to decode JSON that has been converted from JavaScript

When I send an array as a POST request, I first convert it to JSON using the JSON.stringify() method. However, I encountered an issue when trying to decode it in PHP. // JavaScript var arr1 = ['a', 'b', 'c', 'd', & ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

Unexpected error encountered with the release of Angular 2: "Module import of 'ElementRef' resulted in an unexpected value"

After upgrading to Angular 2, I encountered an error related to ElementRef. Initially, I received the error message Angular2 RC5 error:zone.js: Unhandled Promise rejection: No provider for ElementRef which was discussed on this thread. I adjusted my code a ...

Error: The render view is unable to read the 'vote' property of a null object

Within this component, I am receiving a Promise object in the properties. I attempt to store it in state, but upon rendering the view, I encounter the error message "TypeError: Cannot read property 'vote' of null." Seeking a solution to my predic ...