在深拷贝时,会创建一个新的对象,因此在 UI 上更改该对象的属性时,并不会影响原始对象。为了解决这个问题,请在子组件中使用 EventEmitter 来将更改传递回父组件,并在父组件中更新原始对象。
示例代码:
子组件:
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'child-component',
template: `
`,
})
export class ChildComponent {
private innerValue: any = {};
@Input() set value(value: any) {
this.innerValue = { ...value };
}
@Output() valueChange = new EventEmitter();
onModelChange() {
this.valueChange.emit(this.innerValue);
}
}
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: `
`,
})
export class ParentComponent {
originalValue = { prop1: '', prop2: '' };
onValueChange(newValue) {
// 更新原始对象
this.originalValue = newValue;
}
}