setInterval()无法访问Angular2

时间:2016-11-09 23:21:54

标签: angular typescript scope settimeout angular2-directives

我正在尝试创建一个新闻自动收录器指令,将元素滑过其父级,以便您可以读取字符串,如果它太长。我被卡住是因为我无法让setInterval()函数在其当前范围内调用moveLeft()函数,从而将目标元素(this.node1)移过{{1} }。如果我将元素,函数和参数传递给1px,那么DOM就不会被调整,因为我认为元素超出了范围。 如何从setInterval()函数调用当前作用域中的moveLeft()函数?setInterval()函数外部调用时,该函数可以正常工作。

setInterval()

2 个答案:

答案 0 :(得分:3)

首先,在您的原始版本中,您在间隔设置期间执行moveleft,而不是提供该功能。所以它会在你设置时执行,但不会再次执行。

即。 setInterval( this.moveLeft, 100)代替setInterval( this.moveLeft(), 100)

但真正的问题是向setInterval提供一个箭头函数,而不是直接提供函数,因为只需赋予它函数就会改变this的上下文(参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

例如。 setInterval( () => { this.moveLeft(); }, 100)

答案 1 :(得分:1)

在您调用的方法中使用setInterval()

moveLeft() { // slide the elements to the left
    setInterval(() => {
            this.currMargin -= 1;
            this.newMargin = this.currMargin + 'px';
            this.renderer.setElementStyle(this.node1, 'margin-left', this.newMargin);
    }, 100);    
}