Reputation: 3697
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?
Upvotes: 7
Views: 2480
Reputation: 308
Check your module settings, do you have something like this?
StoreModule.forRoot(reducers, {
metaReducers,
runtimeChecks: {
strictStateImmutability: true,
strictActionImmutability: false,
strictStateSerializability: true,
strictActionSerializability: true
}
})
I disabled the strictActionImmutability
property, another alternative is to run ng serve --prod
with the --prod
flag, if you only run ng serve
you need to set to false the strictActionImmutability
property in your runtimeChecks
object
Upvotes: 0
Reputation: 3697
this.modifiedUser
turned out to be indeed readonly. I had to simply make a deep copy of user
object to resolve the issue.
Upvotes: 4