0

I have an angular component, where I define two boolean variables:

  editingPercent: boolean = true;
  editingCap: boolean = false;

In the corresponding html file I have a ceckbox and set this variables in the ts file accordingly:

checkedChanged(e) {
    this.editingPercent = !e.value;
    console.log(this.editingPercent);
    this.editingCap = e.value;
    console.log(this.editingCap);
  }

Everything fine, the console logs false and true.

Now, I want to use this variables elsewhere in the component, in a custom validation callback like this:

  capValidation(e) {
    console.log(this.editingCap + ' ' + e.value);
    if (this.editingCap && e.value === undefined) {
      return false;
    }
    else { return true; }
  }

But the console says, that this.editingCap is undefined. Why?

Thanks.

ps: the validation callback will be simplified to an one row code, if I get this work properly.

derstauner
  • 1,478
  • 2
  • 23
  • 44
  • How do you trigger your callback? from the html? from the typescript? please provide a more complete code example if you can – Marc Sances Nov 14 '20 at 20:11
  • @jonrsharpe, as I saw your comment, I remembered my other question. Sooner or later I will memorize it. Thanks, it was the issue. – derstauner Nov 14 '20 at 20:19
  • Ah, the famous `this` problem. Change your event handler to an arrow function – bahadrdsr Nov 14 '20 at 20:34

1 Answers1

2

Change you event handler to a lambda

checkedChanged = (e) => {
    this.editingPercent = !e.value;
    console.log(this.editingPercent);
    this.editingCap = e.value;
    console.log(this.editingCap);
}
moefinley
  • 1,248
  • 1
  • 13
  • 26