Angular error this.mymethod is not a function

前端 未结 2 1040
灰色年华
灰色年华 2021-01-24 22:12

I\'m trying to create an image slider inside my Angular 5 component. The slider has Previous and Next controls which both work fine but I can\'t get it to slide automatically.

相关标签:
2条回答
  • 2021-01-24 22:51

    change

    setTimeout(this.autoslide, 2000)
    

    to

    setTimeout(this.autoslide.bind(this), 2000)
    

    for this to keep pointing to the current class instance.

    0 讨论(0)
  • 2021-01-24 23:00

    The problem is that when you call setTimeout you pass the function without binding it to the current this. In Javascript this is determined by the caller for functions. You can capture this from the declaration context by using arrow functions or bind:

    setTimeout(this.autoslide.bind(this), 2000)
    // OR
    setTimeout(()=> this.autoslide(), 2000)
    
    0 讨论(0)
提交回复
热议问题