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?
name: [{value: '', disabled: true}, Validators.required],
name: [{value: '', disabled: this.isDisabled}, Validators.required],
or
this.form.controls['name'].disable();
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
this.isDisabled = true;
this.cardForm = this.fb.group({
number: {value: null, disabled: this.isDisabled},
});
and if you change the variable
this.isDisabled = false;
the form will not change. You should use
this.cardForm.get('number').disable();
BTW.
You should use patchValue method for changing value:
this.cardForm.patchValue({
number: '1703'
});
I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean
<fieldset [disabled]="isAnonymous">
<label class="control-label" for="firstName">FirstName</label>
<input class="form-control" id="firstName" type="text" formControlName="firstName" />
</fieldset>