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 ?
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.
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.
Solution. Remove existing formArray by calling clear method on formArray. Then create a new FormArray then update the data source with new controls.
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() ]);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With