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
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)
<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">
export class InformationSectionComponent {
formname = this.formbuilder.group({
firstname: ['']
});
}
Enable whole form
this.formname.enable();
Enable particular field alone
this.formname.controls.firstname.enable();
same for disable, replace enable() with disable().
This Works fine. Comment for queries.
A more general approach would be.
// Variable/Flag declare
public formDisabled = false;
// Form init
this.form = new FormGroup({
name: new FormControl({value: '', disabled: this.formDisabled},
Validators.required),
});
// Enable/disable form control
public toggleFormState() {
this.formDisabled = !this.formDisabled;
const state = this.formDisabled ? 'disable' : 'enable';
Object.keys(this.form.controls).forEach((controlName) => {
this.form.controls[controlName][state](); // disables/enables each form control based on 'this.formDisabled'
});
}
this.form.enable()
this.form.disable()
Or formcontrol 'first'
this.form.get('first').enable()
this.form.get('first').disable()
You can set disable or enable on initial set.
first: new FormControl({disabled: true}, Validators.required)
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>
I had the same problem, but calling this.form.controls['name'].disable() did not fixed it because I was reloading my view (using router.navigate()).
In my case I had to reset my form before reloading:
this.form = undefined; this.router.navigate([path]);