Angular 4 patchValue based on index in FormArray

I want to update formArrayafter the user adds a value to the empty created control.

Currently, when the user selects to add a new element i, created on formArraywith empty values.

buildItem(item?: any, key?: any): FormGroup {
  // Item will pass undefined for initial buildItem in onLoad and new items
  let itemName: string;
  let keyValue: string;
  if (item === undefined) { 
     itemName = ''; key = '' }  
  else { 
     itemName = item.name; keyValue = key 
  };

  /**
   * Builds a single item for form group array in the collectionForm.
   */
   return this.formBuilder.group({ 
                item: [itemName || '', Validators.required], 
                properties: { item, key: key } || {} });
}

This is great for initially creating and updating already added items. The problem is with new items that are added with empty values. When I add a new item, I need to add a return key from firebase toproperties.key

In the save method of this new item, I added patchValue

this.items.patchValue([{ 
         // item being returned from firebase promise
         item: item.name, 
         properties: { item: item.name, key: item.$key' } 
}]);

patchValue . , firebase, , BuildItem(), patchValue

angular formArray,

, , , . REF

, .. , ? , , , . removeAt(idx)

, -

this.form.patchValue.atIndex(this.idx,[{ 
         item: item.name, 
         properties: { item: item.name, key: item.$key' } 
}];

, .. , . , formArray, , , .

, formArray

this.items.push(this.buildItem(...));

this.items.removeAt(this.idx); 

, - .

+4
2

FormArray#at + AbstractControl#patchValue:

this.items.at(index).patchValue(...);
+7

, FormControl, :

this.form.setControl('items',  new FormControl(arrayItemsValue));

:

const items = (<FormArray>this.form.get('items'));
 for (let i = 0; i < items.length; i++) {
     items.removeAt(i);
 }
 this.form.get('items').setValue(arrayItemsValue);
0

Source: https://habr.com/ru/post/1676991/


All Articles