2017-02-11 58 views
5

我有一個被動窗體。在編輯時我想禁用一個控件。如何禁用窗體控件但保留值

以下工作:

this.myForm.controls['analysis_horizon'].disable(); 

但是,關鍵analysis_horizo​​n不再是我的myForm.value哈希值。

如何禁用帶反應形式的字段,但將值保存在表單值散列中?

我試過[禁用] =但我得到以下:

It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true 
     when you set up this control in your component class, the disabled attribute will actually be set in the DOM for 
     you. We recommend using this approach to avoid 'changed after checked' errors. 

     Example: 
     form = new FormGroup({ 
     first: new FormControl({value: 'Nancy', disabled: true}, Validators.required), 
     last: new FormControl('Drew', Validators.required) 
     }); 

我從數據庫中編輯數據加載到表單控件,但我需要一個字段不得更改。

+0

它會告訴你直接在HTML中使用禁用的屬性,而不是用它與formcontrol 。 – micronyks

+0

考慮到它沒有變化,你可以用Object.assign或其他東西把它放回到你自己的值中去。 – jonrsharpe

+0

也許我誤解了,但爲什麼不這樣做,消息建議:'yourFormControl:new FormControl({value:yourPresetValue,disabled:true})' – Alex

回答

10

你可以使用getRawValue()代替財產。根據documentation

FormGroup的聚合值,包括任何禁用的控件。

如果您想要包含所有值,而不管禁用狀態如何,請使用此方法 。否則,屬性是獲取組的值 的最佳方式。

this.myForm.getRawValue() 
0

這裏,如果你不希望使用getRawValue從而改變正從形式價值的正常方式的另一種選擇。更多理由爲什麼我只喜歡只讀:https://stackoverflow.com/a/7730719/1678151

我的解決方案還顯示如何填寫表單控件。

component.ts

fillForm(data: any){ 
if (data != null && data.firstName){ 
    this.form.patchValue({ 
    firstName: data.firstName 
    })  
    this.firstNameIsReadOnly = true; 
} 

template.html

<input formControlName="firstName" [readonly]='firstNameIsReadOnly'> 

styles.scss

input[readonly] { 
color: rgba(0,0,0,.38); 
} 
相關問題