0

Please check below code, I want to increment the count and based on the count I want to change the backgroundColor variable in typescript (angular). Problem is when changeColor() function is invoke count is not increment and backgroundColor is showing undefined.

export class AppComponent {
  title = "angularExample";
  backgroundColor = "yellow";

  changeColor() {
    let count = 0;
    function displayNumber() {
      alert(++count + this.backgroundColor);
    }
    displayNumber();
  }
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
skm
  • 71
  • 1
  • 1
  • 11

1 Answers1

3

You should use an arrow function for this, because this is no longer the this you expect:

changeColor() {
  let count = 0;
  const displayNumber = () => {
    alert(++count + this.backgroundColor);
  };
  displayNumber();
}

Although, can't really see a reason why you want to do something like this :)

It's better to just use the class fields:

export class AppComponent {
  title = "angularExample";
  backgroundColor = "yellow";
  count = 0;

  changeColor() {
    this.displayNumber();
  }

  displayNumber() {
    alert(++this.count + this.backgroundColor);
  }
}

Or if you really want to use a closure (which is an immediately invoked function expression), I guess you can do something like this:

export class AppComponent {
  // ...
  changeColor = ((count: number) => () => alert(++count + this.backgroundColor))(0);
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • Now 'this' is working counter is not increase in second click. yes, in html , I have one div, in first click I have to change the color of div to red and second click change div color to green so on. – skm Dec 10 '19 at 19:25
  • @susantakumarmuduli updated my answer with a more reasonable solution – Poul Kruijt Dec 10 '19 at 19:26
  • @PierreDue. Thanks It is working. is there any way to make count variable to local scope so that other function can not used this count variable or it should not pollute by other function, like how closure is working – skm Dec 10 '19 at 19:35
  • 1
    @susantakumarmuduli I've updated my answer with also a closure example. I don't know if you should do it like that, because it makes your code a bit messy. Better would be to just make the variable `private` and don't bother too much about things polluting. It's part of the class, so it should stay there – Poul Kruijt Dec 10 '19 at 19:38