Search code examples
angulartypescriptangular-reactive-formsangular14formgroups

Angular Reactive Form - How to enable all form controls at once


I have a reactive form with some 35 fields. All 35 controls should be disabled when the page loads. But on click of the 'Edit' button, all those 35 controls should get enabled. This is what I tried:

HTML

<form ...>
    Email input field...
    Contact input field...
    33 other fields...
</form>

<button (click)="allowFormUpdate()">Edit</button>

TS

formUpdateStatus: boolean = true; // VARIABLE TO INITIALLY DISABLE THE FIELDS
myReactiveForm;

allowFormUpdate() {
    this.formUpdateStatus = false; // NOT WORKING
    this.myReactiveForm.controls['email'].enable();
    this.myReactiveForm.controls['contact'].enable();
    this.myReactiveForm.controls['firstName'].enable();
    ...
    // Code being repeated
}

ngOnInit(): void {
    ...
    this.myReactiveForm= new FormGroup({
      email: new FormControl({value: '...', disabled: this.formUpdateStatus}),
      contact: new FormControl({value: '...', disabled: this.formUpdateStatus}),
      firstname: new FormControl({value: '...', disabled: this.formUpdateStatus}),
      ...     

When I clicked on the 'Edit' button, my method allowFormUpdate() was called but noticed that in that method I had to enable each control one by one because this.formUpdateStatus = false; didn't work. Please help me enable all the fields in one shot.


Solution

  • You can enable all the form controls in the FormGroup via:

    this.myReactiveForm.enable();
    

    Same goes for you can disable all the form controls by disabling the FormGroup without having to disable each FormControl with the disabled value.

    this.formUpdateStatus && this.myReactiveForm.disable();
    

    Demo @ StackBlitz