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.
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With