![](/img/trans.png)
[英]How to make sure angular reactive form setValue/patchvalue is complete
[英]Assigning a reactive form control in Angular 4 to disabled, not sure how or if to use patchValue
我的應用程序中有一個用戶表單。 我以“反應式表單”方式在組件中創建表單。 在某些情況下,我想設置表單控件,以使其處於禁用狀態,並且用戶無法與其進行交互。 我的(精簡的)代碼看起來像這樣...
constructor(private usersService: UsersService, private formBuilder: FormBuilder) {}
// I create the readonly boolean
public isReadOnly: boolean = false;
private buildMyForm(): void {
this.userForm = this.formBuilder.group({
StatusID: [{value: '', disabled: this.isReadOnly}, Validators.required],
AddressID: [{value: '', disabled: this.isReadOnly}, Validators.required],
Comments: [{value: '', disabled: this.isReadOnly}, Validators.maxLength(250)],
Description: [{value: '', disabled: this.isReadOnly}, Validators.maxLength(250)],
});
}
public ngOnInit(): void {
this.buildForm(); // create the form
this.usersService.loadUser().subscribe((response:UserData) => {
// lots of info but we are interested in response.readonly which is a boolean
if(response.readonly) {
this.isReadOnly = response.readonly;
}
});
}
如您所見,我確定僅在usersService.loadUser()
返回值之后是否才應該讀取表單,現在此時我的formBuilder已經構造了該表單,並且如果response.readonly
為,則disabled
狀態不會受到影響。真正。 我應該移動this.buildForm();
進入訂閱時,由於HTML需要formBuilder [formGroup]="userForm"
導致應用錯誤。 我一直在閱讀如何更新表單控件,但到目前為止沒有任何效果,我認為我可以像這樣使用.patchValue
if(response.readonly) {
this.isReadOnly = response.readonly;
this.userForm.patchValue({
// set the disabled status for StatusID, AddressID:, Comments:, Description
});
}
但是我不確定這是否是正確的方法...我不想更新值? 我目前正在閱讀文檔,但通常這里的人要比我快得多,因此,如果有人可以幫助您,請向我指出正確的方向。
在忘記之前 -我知道我可以使用[disabled]="isReadOnly"
或[readonly]="isReadOnly"
將條件添加到HTML模板中,我只是認為在組件中包含邏輯是一種更好的方法,而不是模板...
您可以enable()
以啟用禁用字段
通過控制啟用字段
this.userForm.controls.StatusID.enable();
或簡單地
this.userForm.enable();
將啟用所有禁用的字段
我找到了答案,就是將項目設置為禁用,如下所示:
if(response.readonly) {
this.userForm.get('StatusID').disable();
this.userForm.get('AddressID').disable();
this.userForm.get('Comments').disable();
this.userForm.get('Description').disable();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.