Home > Mobile >  How to enable all form controls at once in an Angular 14 reactive form
How to enable all form controls at once in an Angular 14 reactive form

Time:12-12

I've a reactive form with some 35 fields. All the 35 controls should be disabled when the page loads. But on click of '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 'Edit' button, my method allowFormUpdate() was called but notice that in that method I've to enable each control one by one because this.formUpdateStatus = false; didn't work. Please help me enable all the fields in one shot.

CodePudding user response:

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

  • Related