2017-10-09 54 views
6

我試圖實現通過下面的代碼雙向結合閱讀:活性形式的雙向綁定錯誤:無法分配唯一的財產

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]'。任何想法爲什麼?

+0

我在您的模板中看不到'userForm'。你能創造蹲伏嗎? – yurzui

+0

對不起,這只是一個錯字,'userForm'不是'form'。 – Sammy

+0

你從服務獲得的_this.modifiedUser.subscribed_值是多少? –

回答

4

this.modifiedUser原來確實是只讀的。我不得不簡單地製作user對象的深層副本來解決問題。

相關問題