Angular “this is undefined” when trying to increment number variable, not sure what I’m doing wrong Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Angular “this is undefined” when trying to increment number variable, not sure what I’m doing wrong without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m basically counting the number of times an object in an array has 2 keys that equals a certain value. I want to increment that number for each time the condition is met.

if I console.log to see the number of times the ‘for’ loop is firing, everything is good and all works well. But when I try to do something with this.multidropAccepted I’m suddenly getting undefined errors, even when I’m just trying to read it on the console.

Code:

function countAccepted(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].DeliveryStatus == "Accepted" && arr[i].BookingId == "0") {
      console.log("poop");
      this.multidropAccepted++;
    }
  }
}

Answer

If you’re using Angular with typescript then don’t use function keyword to write method. As it’ll create its own scope & thus you’ll not be able to access class level properties using this inside it. Update your method code to:

countAccepted(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].DeliveryStatus == "Accepted" && arr[i].BookingId == "0") {
      console.log("poop");
      this.multidropAccepted++;
    }
  }
}
We are here to answer your question about Angular “this is undefined” when trying to increment number variable, not sure what I’m doing wrong - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji