英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论