我的输入设置器为什么在没有更改的情况下被调用?

huangapple go评论58阅读模式
英文:

why is my input setter called even without changes

问题

我有一个典型的输入的setter/getter在我的代码中,因为我想在值更改时执行一个函数,但不知何故它在没有输入更改的情况下被触发。

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

问题在于doStuff方法被调用太多次,因为我以恒定的方式收到一个空列表。我只想在有更改时才触发setter。

英文:

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

答案1

得分: 1

每当你得到一个空列表并将其赋值给输入变量(这部分代码我们看不到),输入就会发生变化。它将获得一个新的对象(列表),该对象是空的。对于你来说,数据没有变化,但对于Angular来说,引用发生了变化。

为了使其正常工作,只需在setter方法中检查列表是否包含任何元素。如果是的话,然后调用 doStuff。或者更好的方法是在父组件中检查它,并仅在列表不为空时设置输入变量。

英文:

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.

答案2

得分: -1

你可以避免使用setter和getter,只需使用OnChanges接口与ngOnChanges(changes: SimpleChanges): void方法来监听所有@Input()的变化。

@Input() _myInput: string[];

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

我认为这样可以让代码更简单和可读。为什么不使用Angular提供的生命周期钩子呢?祝编码愉快。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月25日 22:45:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定