Home > Software design >  How to selectively enable/disbale a particular form control in a reactive form
How to selectively enable/disbale a particular form control in a reactive form

Time:12-14

I've created a reactive form in Angular 14. I've some 25 fields. I wanted the form to be in disabled mode initially when the page loads. I was doing this:

ngOnInit() {
    this.myForm= new FormGroup({
      leNumber: new FormControl(''),
      leName: new FormControl(''),
      leAddrLine1: new FormControl(''),
      leNumberStartDate: new FormControl(''),
      // 21 more fields
    });

    // initially disable the entire form when page loads
    this.myForm.disable();
}

I've an EDIT button on UI. On click of this button the form should get enabled:

<button (click)="enableForm()">Allow Edit</button>

enableForm() {
    this.myForm.enable();
}

The requirement is that on click of EDIT button all the fields should get enabled except leName and leStartDate and there are few more like that. How to achieve this kind of selective enabling/disabling of the fields. Please help.

CodePudding user response:

You could do the following:

enableForm() {
    Object.entries(this.myForm.controls)
      .filter(([key, value]) => ['leNumber', 'leStartDate'].indexOf(key) < 0 )
      .forEach(([key,value]) => value.enable());
    //this.myForm.enable();
  }

This will loop through all your formControls and enable only the ones not contained in the array. Nevertheless in your case it could make sense to split your formGroup up into two separate ones and only enable the one where the edit-feature is available, but this is highly depending on your use-case.

The reason is that the proposed approach is not really performant in any way and will trigger change detection for each form control, which could be avoided.

  • Related