如果传递一个带有嵌套对象的复杂对象作为输入,angular并不总是检测到对该复杂对象所做的更改。如何解决?
伪代码示例:
template: `<child-component [complexObject]="complexObject"></child-component>`
ParentComponent {
complexObject = {
nestedObject: {
username: ''
}
}
changeComplexObject() {
this.complexObject.nestedObject.username = 'John Doe';
}
}
ChildComponent {
private _complexObject: any;
@Input()
public set complexObject(value: any) {
this._complexObject = value;
this.doSomethingWithComplexObject();
}
doSomethingWithComplexObject() {
// stops working after 1 or 2 changes
}
}
也尝试了ngOnChanges,但行为是一样的。在复杂对象发生1或2次变化后,angular简单地停止检测该对象的变化。它适用于值类型,例如数字或字符串。
我认为这是由于对引用项(数组和对象(的更改检测。它们将值保存在内存中,因为这不会改变,所以更改检测不会启动
我要做的是,每当我必须更新对象时,无论有多少嵌套数组和对象,我都会不固定地更新。
试试你的父组件:
template: `<child-component [complexObject]="complexObject"></child-component>`
ParentComponent {
complexObject = {
nestedObject: {
username: ''
}
}
changeComplexObject() {
this.complexObject = {
...this.complexObject,
nestedObject: {
...nestedObject,
userName: 'John Doe',
}
}
}
}
希望当您更改对象和嵌套对象的ram位置时,更改检测应该会启动