Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to selectively enable/disbale a particular form control in a reactive form

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading