angularangular-input

why is my input setter called even without changes


I have typical setter/getter for an input in my code, as I want to execute a function when the value changes, but somehow it is fired without input changes

private _myInput: string[]: [];
@Input()
get myInput(): string[] {
  return this._myInput;
}
set myInput(myInput[]) {
  this._myInput = myInput;
  this.doStuff();
}

the problem doStuff method is called too many times because i receive an empty list in a constant way. I only want the setter get fired when there is changes


Solution

  • Every time you get an emtpy list and assign it to the input variable (this part of code we don't see) the input is changing. It will get a new object (list), which is empty. For you, there is no change in the data, but for Angular there is a change in the reference.

    In order to get this working, simply check in the setter method if the list contains any element. If yes, then call doStuff. Or even better: check for it in the parent component and set the input variable only if the list isn't empty.