FormArray patchValue() patchValue() patches the value of FormArray . We need to pass an array to patchValue() that should match the structure of control either completely or partially. In patchValue() it is not necessary to pass an array that should exactly match the structure of control.
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.
First, we need to import the FormArray from the Angular Forms Module. Build a formGroup orderForm using the FormBuilder. We define items as FormArray. We need to capture two fields under each item, the name of the item & description and price.
Use FormArray#at
+ AbstractControl#patchValue
:
this.items.at(index).patchValue(...);
DEMO
You can do this simply by creating a new FormControl if you want to update the hole array structure:
this.form.setControl('items', new FormControl(arrayItemsValue));
Or by removing all items before updating them :
const items = (<FormArray>this.form.get('items'));
for (let i = 0; i < items.length; i++) {
items.removeAt(i);
}
this.form.get('items').setValue(arrayItemsValue);
As developer033 said:
Use FormArray#at + AbstractControl#patchValue
But how to? Here's an example:
In the HTML:
<div formArrayName="alternateEmail" *ngFor="let control of alternateEmail.controls; index as i">
<input type="text" placeholder="Type an alternative email" [formControlName]="i"><input>
</div>
In the class:
get alternateEmail(){ return this.registrationForm.get('alternateEmail') as FormArray }
And the actual patch method:
patchDynamicFormBlockValue(){
this.alternateEmail.at(<index>).patchValue('[email protected]')
}
You can also remove the as FormArray
and cast just when you need:
(<FormArray>this.alternateEmail).at(<index>).patchValue('[email protected]')
let rows = this.manageOrderForm.get('ordersForm') as FormArray;
rows.controls[this.index].patchValue({totalAmount:totalPrice});
this.index = this.index + 1;
formarray set value at index
((this.form.get('controls') as FormArray).at(index) as FormGroup).get('description').patchValue(item.description);
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