0

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

cucuru
  • 3,456
  • 8
  • 40
  • 74

2 Answers2

1

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.

derstauner
  • 1,478
  • 2
  • 23
  • 44
-1

You can avoid setter and getter and simply use the OnChanges interface with the ngOnChanges(changes: SimpleChanges): void Method to listen to all @Input() changes.

  @Input() _myInput: string[]: [];

  ngOnChanges(changes: SimpleChanges) {
     this.doStuff();
  }

I guess this makes the code more simpler and readable. Why not use the life cycle hooks which angular provides. Happy coding.