当输入不是原始类型(数字/字符串/布尔值)时,您所描述的行为就会发生。如果它是一个复杂对象(不同于 null)并且您更改了对象的任何属性,那么该更改将反映在父对象上,因为它是相同的:您处理的是引用,而不是值。
如果您想避免这种情况,您必须对输入进行深度克隆,如下所示:
private _data: any;
@Input() set data(d: any) {
// If you want to improve performance, use this library to do a deep clone:
// https://github.com/planttheidea/fast-copy
// otherwise, you can go with JSON.parse(JSON.sringify(...))
this._data = d ? JSON.parse(JSON.sringify(d)) : null;
}
get data(): any {return this._data;}
补充信息
现在,作为信息:如果您愿意,可以真正使用 2 路数据绑定:
@Input() data:any = {}
// mandatory: the same name of the @Input, suffixed with "Change"
@Ouput() dataChange = new EventEmitter<any>();
然后您可以在父级中使用“banana-in-the-box”表示法:
<app-config-form [(data)]="param"></app-config> //param is ngModel
但更新不会自动触发。每次在child里改,都要调用this.dataChange.emit(value)。
例如(在孩子身上):
buttonClickHandler() {
this.data = 2;
this.dataChange.emit(2);
}