Angular error this.mymethod is not a function

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.

<!-- language: lang-typescript -->
import { Component, OnInit, ElementRef, Renderer2 } from '@angular/core';
@Component({...})
export class HomeComponent implements OnInit {

  private slides;
  private dots;
  private slideIndex: any = 1
  private len;

  constructor(private el: ElementRef, private renderer: Renderer2) {
  }

  ngOnInit() {
    /* Gets a nodelist of the slider images in the DOM */
    this.slides = this.el.nativeElement.querySelectorAll(".slide");
    /* The control dots at the bottom of the slider */
    this.dots = this.el.nativeElement.querySelectorAll(".slider__dots > *")
    this.len = this.slides.length

    this.showImage(this.slideIndex)
    this.autoslide() /* Errors out with the message "this.imageCycle is not a function" */
  }

  /* The main slider method */
  showImage(n) {

    if (n > this.len) { this.slideIndex = 1 }
    if (n < 1) { this.slideIndex = this.len }

    for (let i = 0; i < this.len; i++) {
      this.renderer.setStyle(this.slides[i], 'display', 'none')
      this.renderer.removeClass(this.dots[i], 'active-dot')
    }

    this.renderer.addClass(this.slides[this.slideIndex-1], 'fade')
    this.renderer.setStyle(this.slides[this.slideIndex-1], 'display', 'block')
    this.renderer.addClass(this.dots[this.slideIndex-1], "active-dot")
  }


  /* Cycles through the images, either previous or next */
  imageCycle(n) {
    this.showImage(this.slideIndex += n)
  }

  /* Handles the dots */
  currentImage(n) {
    this.showImage(this.slideIndex = n)
  }

  /* Automatically slide through the images */
  autoslide() {
    this.imageCycle(1)
    setTimeout(this.autoslide, 2000)
  }
}

My Next and Previous buttons both call the imageCycle() method passing in 1 for next and -1 for previous as the parameters. Both these buttons work fine. However, I would also like for the slider to slide automatically hence the autoslide method but upon calling it, it errors out with the message "TypeError: this.imageCycle is not a function". What am I doing wrong? I'd really appreciate some help.

Answers:

Answer

change

setTimeout(this.autoslide, 2000)

to

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

for this to keep pointing to the current class instance.

Answer

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)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.