I'm trying to achieve two way binding via the following code:
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>
However, I'm always getting the error TypeError: Cannot assign to read only property 'subscribed' of object '[object Object]'
in the console as soon as the form appears. Any idea why?
this.modifiedUser
turned out to be indeed readonly. I had to simply make a deep copy of user
object to resolve the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With