Search code examples
angularangular9nouislider

ERROR TypeError: Cannot read property 'call' of undefined


I finally got to start making the nouislider work in my angular 9 project. My issue now is that I want to update a field when the slider value changes (so when the user moves the slider, I want to display the new value on the screen). There is an issue with the events and I'm not sure what it is.

noUiSlider.create(this.theHtmlElement, {
  start: [3000],
  step: 1,
  connect: [true, false],
  range: {
      'min': [0],
      'max': [10000]
  }
});

this.theHtmlElement.noUiSlider.on('update', this.valueChanged());


...
valueChanged() {
console.log(this.theHtmlElement.noUiSlider.get());

}

The error I get is:

ERROR TypeError: Cannot read property 'call' of undefined
at nouislider.js:2082
at Array.forEach (<anonymous>)
at nouislider.js:2081
at Array.forEach (<anonymous>)
at fireEvent (nouislider.js:2077)
at nouislider.js:2055
at Array.forEach (<anonymous>)
at Object.bindEvent [as on] (nouislider.js:2054)
at AddCreditPageComponent.ngAfterViewInit (add-credit-page.component.ts:65)
at callProviderLifecycles (core.js:33986)

The event seems to work the first time, I get to see the initial value in console but then it's followed by the error! and then nothing else works. I had a walk through, there seem to be a second scope event which is undefined or something! not sure what it is and where it's coming from, it's probably that one thats causing the problem. I'm not sure how to fix it.


Solution

  • To bind an event, you have to pass in an anonymous function (among other possibilities);

    this.theHtmlElement.noUiSlider.on('update', () => this.valueChanged());
    

    or

    this.theHtmlElement.noUiSlider.on('update', this.valueChanged.bind(this));
    

    or

    this.theHtmlElement.noUiSlider.on('update', this.valueChanged);
    
    readonly valueChanged = () => {
      console.log(this.theHtmlElement.noUiSlider.get());
    };
    

    How you did it immediately executes the this.valueChanged() method, which returns undefined. It then tries to bind this undefined to the update event handler, which will result in the error you see