Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create disabled form group with FormBuilder

Let's say we have myFormGroup which is initialized via FormBuilder:

this.myFormGroup = this.fb.group(
  {
    field1: ['', SomeValidator1],
    field2: ['', AnotherValidator2],
    field3: [''],
    ...
  }
);

I'm aware that we can disable particular form control, for instance:

fb.control({value: 'my val', disabled: true});

Of course I can use this syntax in my example and mark as disabled every single control in the group. But the form group might have a lot of controls.

So the question - is there any way to disable entire FormGroup/FormArray while creating (not after) it via FormBuilder?

p.s. The reason I'm asking this question is because I need conditionally initialize form group with active or disabled fields for different kind of user privileges.

like image 530
shohrukh Avatar asked Aug 21 '18 15:08

shohrukh


3 Answers

I had same problem, Angular FormBuilder receives, initial state of control, and verify if the param its like to { value: any, disabled: boolean, ..... } if the parameter meets this struct, initialize the control with value and disabled/active.

try:

this.myFormGroup = this.fb.group(
  {
    field1: [{ value: '', disabled: true }, SomeValidator1],
    field2: [{ value:'', disabled: true }, AnotherValidator2],
    field3: [{ value:'', disabled: true}],
    ...
  }
);
like image 197
Luis Felipe Diaz Valbuena Avatar answered Oct 20 '22 21:10

Luis Felipe Diaz Valbuena


I didn't find any better solution than just disable the group right after its creation.

// original code
this.myFormGroup = this.fb.group({
  field1: ['', SomeValidator1],
  field2: ['', AnotherValidator2],
  field3: [''],
  ...
});
// added
this.myFormGroup.disable();

This solution is better than Luis Felipe Diaz Valbuena's, because you don't need to { disable: true } each field. Imagine doing this for 10+ fields.

like image 40
Halfist Avatar answered Oct 20 '22 20:10

Halfist


Try this code:

enableForm(group: FormGroup, enable:boolean) {
   for (const i in group.controls) {
      if(enable) {
        group.controls[i].enable();
      } else {
        group.controls[i].disable();
      }
   }
}
like image 27
Mukesh Kumar Avatar answered Oct 20 '22 21:10

Mukesh Kumar