gpt4 book ai didi

angular - Reactive Forms双向绑定(bind)错误: Cannot assign to read only property

转载 作者:太空狗 更新时间:2023-10-29 17:26:58 24 4
gpt4 key购买 nike

我正在尝试通过以下代码实现双向绑定(bind):

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]'。知道为什么吗?

最佳答案

this.modifiedUser 结果确实是只读的。我不得不简单地制作一个 user 对象的深拷贝来解决这个问题。

关于angular - Reactive Forms双向绑定(bind)错误: Cannot assign to read only property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46651210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com