Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive Forms two-way binding error: Cannot assign to read only property

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?

like image 596
Sammy Avatar asked Oct 09 '17 16:10

Sammy


Video Answer


1 Answers

this.modifiedUser turned out to be indeed readonly. I had to simply make a deep copy of user object to resolve the issue.

like image 176
Sammy Avatar answered Sep 28 '22 23:09

Sammy