Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable form control but keep value

Tags:

angular

I have a reactive form. On edit I want a control disabled.

The below works:

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

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

How do I disable a field with a reactive form but keeping the value in the form values hash?

I tried [disabled]= but I get the below:

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 on edit into the form controls but I need one field to not be allowed to change.

like image 280
Tampa Avatar asked Feb 11 '17 20:02

Tampa


People also ask

Can I use form control without form?

Angular FormControl is an inbuilt class used to get and set values and validate the form control fields like <input> or <select>. The FormControl tracks the value and validation status of an individual form control. It can be used standalone as well as with a parent form.


2 Answers

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

The aggregate value of the FormGroup, including any disabled controls.

If you'd like to include all values regardless of disabled status, use this method. Otherwise, the value property is the best way to get the value of the group.

this.myForm.getRawValue() 
like image 192
I. Ajeneza Avatar answered Sep 21 '22 11:09

I. Ajeneza


My solution is using [attr.disabled]:

<select formControlName="foo"   [attr.disabled]="disabled == true ? true : null">  </select> 

Assuming you have a disabled property in your component. You have to retun null not false to enable the input.

like image 23
pogiaron Avatar answered Sep 21 '22 11:09

pogiaron