我正在尝试通过以下代码实现双向绑定:
export interface User {
name: string;
subscribed: boolean;
}
export class UserEditComponent implements OnInit {
modifiedUser: User;
userForm: FormGroup;
ngOnInit() {
this.userForm = this.fb.group({
name: ['', Validators.required],
subscribed: false
});
this.route.paramMap.switchMap((params: ParamMap) => {
return this.userService.getUser(params.get('id'));
}).subscribe((user) => {
this.modifiedUser = user;
this.userForm.setValue({
name: this.modifiedUser.name,
subscribed: this.modifiedUser.subscribed
});
});
this.userForm.valueChanges.subscribe((data) => {
this.modifiedUser.subscribed = data.subscribed;
});
}
}
<form [formGroup]="userForm">
<textarea class="form-control" formControlName="name">{{modifiedUser.name}}</textarea>
<input type="checkbox" class="custom-control-input" formControlName="subscribed">
</form>
但是,一旦表单出现,我总是在控制台中收到错误TypeError: Cannot assign to read only property 'subscribed' of object '[object Object]'
。知道为什么吗?
答案 0 :(得分:4)
.thumb-wrapper
结果证实确实是只读的。我只需要制作一份this.modifiedUser
对象的深层副本来解决问题。
答案 1 :(得分:0)
检查您的模块设置,您是否有类似的东西?
StoreModule.forRoot(reducers, {
metaReducers,
runtimeChecks: {
strictStateImmutability: true,
strictActionImmutability: false,
strictStateSerializability: true,
strictActionSerializability: true
}
})
我禁用了strictActionImmutability
属性,另一种选择是使用ng serve --prod
标志运行--prod
,如果仅运行ng serve
,则需要将{{ 1}}属性中的strictActionImmutability
对象