I already tried to follow the example of other answers from here and I did not succeed!
I created a reactive form (ie, dynamic) and I want to disable some fields at any given time. My form code:
this.form = this._fb.group({
name: ['', Validators.required],
options: this._fb.array([])
});
const control = <FormArray>this.form.controls['options'];
control.push(this._fb.group({
value: ['']
}));
my html:
<div class='row' formArrayName="options">
<div *ngFor="let opt of form.controls.options.controls; let i=index">
<div [formGroupName]="i">
<select formArrayName="value">
<option></option>
<option>{{ opt.controls.value }}</option>
</select>
</div>
</div>
</div>
I reduced the code to facilitate. I want to disable the field of type select. I tried to do the following:
form = new FormGroup({
first: new FormControl({value: '', disabled: true}, Validators.required),
});
not working! Does anyone have a suggestion?
The best solution is here:
https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110
Outline of solution (in case of broken link):
(1) Create a directive
(2) Use it like so
(3) Since disabled inputs do not show in form.value on submit you may need to use the following instead (if required):
If to use
disabled
form input elements (like suggested in correct answer how to disable input) validation for them will be also disabled, take attention for that!(And if you are using on submit button like
[disabled]="!form.valid"
it will exclude your field from validation)Pay attention
If you are creating a form using a variable for condition and trying to change it later it will not work, i.e. the form will not change.
For example
and if you change the variable
the form will not change. You should use
BTW.
You should use patchValue method for changing value:
To make a field disable and enable of reactive form angular 2+
1.To disable
<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">
To enable
Enable whole form
this.formname.enable();
Enable particular field alone
this.formname.controls.firstname.enable();
This Works fine. Comment for queries.
The
disabling
FormControlprevents
it to be present in a form whilesaving
. You can just set it thereadonly
property.