Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update controls of FormArray

My form group code is as

this.myForm = this._fb.group({            
            branch_name: ['', [Validators.required]],
            branch_timing: this._fb.array([
                this.initBranchTiming(),
            ])                                
        });

initBranchTiming() {       
        return this._fb.group({
            day: ['', []],
            open_from: ['00:00:00', []],
            open_till: ['00:00:00', []]           
        });
  }

branch_name is updated by this code

(<FormControl>this.myForm.controls['branch_name']).updateValue(this.branch_detail.branch_name);

Now i have to update the 'day' field of form array. what to do to update the 'day' field of form array branch_timing ?

like image 204
Mubashir Avatar asked Aug 30 '16 13:08

Mubashir


People also ask

How do I validate FormArray controls?

Validating Angular FormArray First you need to add the required validators while creating a new product form group inside the addProduct method. Now let's add a span element adjacent to the input control. Add the following CSS to the app. component.

How do you clear FormArray controls?

You can manually clear each FormArray element by calling the removeAt(i) function in a loop. The advantage to this approach is that any subscriptions on your formArray , such as that registered with formArray. valueChanges , will not be lost.

How do you refresh a form array?

Solution. Remove existing formArray by calling clear method on formArray. Then create a new FormArray then update the data source with new controls.

How do you set values on FormArray?

FormArray setValue() setValue() sets the value of the FormArray . We need to pass an array that matches the structure of the control. Create a sample FormArray . myFormArray = new FormArray([ new FormControl(), new FormControl(), new FormControl() ]);


1 Answers

AFAIK putting a FormGroup inside of a FormArray strips the 'FormControls' of their names and makes it just a list, like a normal array.

In order to update the FormControls individually, you update the value of each AbstractControl from the FormGroup by using the index:

let index = 0; // or 1 or 2
(<FormArray>this.myForm.controls['branch_timing']).at(index).patchValue('example');

Or you can update the entire FormArray by calling setValue or patchValue:

(<FormArray>this.myForm.controls['branch_timing']).setValue(['example', 'example1', 'example2']);

setValue requires an array that matches the entire structure or the FormArray, while patchValue can take a super-set or sub-set of the array. (FormArray-class on Angular2's website)

like image 70
Federico Pettinella Avatar answered Sep 20 '22 08:09

Federico Pettinella