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.
      }
    })

  });
}

}
2

1 Answer 1

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;
      }
    })
  });
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Bingo. You did great. I went with the first technique and it solved my problem. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.