Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 patchValue based on index in FormArray

People also ask

How do you use patchValue in FormArray?

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.

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 does Angular define FormArray?

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);