2

I'm new to Angular 2 and I'm building an app. I want to update the variable value on view with setInterval() function. The function is executed but the view is not geting updated with the value of 'title' which updates every second:

public title: number;
public t = setInterval(this.test, 1000);
test() {
    var i: number = Math.random();
    this.title = i;
    console.log(i);
}

This code does not update the view. But after changing to this code, it works:

public title: number;
public t = setInterval(() => { this.test(); }, 1000);
test() {
    var i: number = Math.random();
    this.title = i;
    console.log(i);
}

The console.log(i) prints correct values in both cases everytime its called. When checked using Chrome debugger, the value of 'this.title' is getting updated by 'i'. Its just that the value is not getting updated in View.

Swanand Pangam
  • 858
  • 1
  • 10
  • 25
  • 2
    When you call with arrow function `() => ` `this` binds to your class, but if you do not do that `this` binds to setInterval function scope. So if you do not want to use arrow function just bind test with your class with `this.test.bind(this)` – Miguel Lattuada Jul 21 '17 at 13:16
  • 1
    Yeah, it took me a while to understand, it's a context problem. The value of `this` differs in both cases. – Jeremy Thille Jul 21 '17 at 13:17
  • I hope this comment will help someone. In my case the problem was the option ```@Component(){ changeDetection: ChangeDetectionStrategy.onPush}``` – Niko Oct 18 '20 at 10:02

1 Answers1

0

The first version is not using arrow functions, therefore this.test is probably not found and throwing an error. Check the chrome developer console log.

The second version is using the arrow function, which will scope this to the parent code block and make the test function available to be executed.

Sonu Kapoor
  • 1,567
  • 3
  • 16
  • 34