Two-way forms binding reactive error: cannot read-only property

I am trying to achieve two way binding with 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>
Run codeHide result

However, I always get an error message TypeError: Cannot assign to read only property 'subscribed' of object '[object Object]'in the console as soon as the form appears. Any idea why?

+6
source share
1 answer

this.modifiedUserturned out to be really read-only. I just had to make a deep copy of the object userto solve the problem.

+4
source

All Articles