How to disable form control but retain value

I have a reactive form. When editing, I want the control to be disabled.

The following is shown:

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

However, key Analysis_horizon is no longer in my myForm.value hash.

How to disable a field with a reactive form, but keeping the value in the form hash value?

I tried [disabled] =, but I get the following:

 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) }); 

I load data from my database when editing into form controls, but I need one field to not be allowed to change.

+5
source share
2 answers

You can use getRawValue () instead of the value property. According to the documentation :

The cumulative value of a FormGroup, including any disabled controls.

If you want to enable all values ​​regardless of the disabled state, use this method. Otherwise, the value property is the best way to get the value of the group.

 this.myForm.getRawValue() 
+11
source

Here is another option if you do not want to use getRawValue, which changes the usual way of getting values ​​from forms. More reasons I like to read only better: fooobar.com/questions/16937 / ....

My solution also shows how to fill out a form control.

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); } 
0
source

Source: https://habr.com/ru/post/1264105/


All Articles