0

I'm trying to set a Boolean property which is nested within two forEach loops.

The loops work fine, but I get an error that says: TypeError: Cannot set property 'hasAtLeastOne' of undefined.

Does anyone have any ideas?

Thanks.

export classItemComponent implements OnInit {

hasAtLeastOne: boolean = false;


onSubmit(event) {
    this.hasAtLeastOne = false;
    this.user.Item.forEach(function (value) {

    value.ItemMemberships.forEach(function (value) {

      if (value.ItemMembershipActive == 1)
      {
         this.hasAtLeastOne = true;        // This line fails.
      }
    })

  });
}

}
dev1998
  • 882
  • 7
  • 17
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Matt McCutchen Aug 28 '18 at 18:45
  • 1
    See here: https://stackoverflow.com/questions/19707969/the-invocation-context-this-of-the-foreach-function-call – Chris Cousins Aug 28 '18 at 18:46

1 Answers1

5

Inside your loop function this is not anymore bind to your component.

You have 3 solutions :

Use an alias for this :

hasAtLeastOne: boolean = false;

onSubmit(event) {
  var self = this;
  this.hasAtLeastOne = false;
  this.user.Item.forEach(function (value) {
    value.ItemMemberships.forEach(function (value) {
      if (value.ItemMembershipActive == 1) {
        self.hasAtLeastOne = true;
      }
    })
  });
}

Bind this in loop functions

hasAtLeastOne: boolean = false;

onSubmit(event) {
  this.hasAtLeastOne = false;
  this.user.Item.forEach(function (value) {
    value.ItemMemberships.forEach(function (value) {
      if (value.ItemMembershipActive == 1) {
        this.hasAtLeastOne = true;
      }
    }.bind(this))
  }.bind(this));
}

Use arrow functions (ES6) :

hasAtLeastOne: boolean = false;

onSubmit(event) {
  this.hasAtLeastOne = false;
  this.user.Item.forEach(item => {
    item.ItemMemberships.forEach(itemMember => {
      if (itemMember.ItemMembershipActive == 1) {
        this.hasAtLeastOne = true;
      }
    })
  });
} 
JeRivals
  • 264
  • 1
  • 6