Search code examples
angularangular-formsangular-reactive-formsformarray

Patching Array Inside An Array Using Reactive Forms in Angular


I'm trying to display the details FormArray inside the rows FormArray. I need help since I can't display the data of the details FormArray. I only know how to display the rows FormArray but the details FormArray is much difficult for me. Here's what i have tried below. PLEASE SEE THIS STACKBLITZ FILE THAT I'VE CREATED.

CLICK THIS LINK

Thank you.

  patchValues() {
        let rows = this.myForm.get('rows') as FormArray;
        this.orders.sales.deliveries.forEach(item => {
            rows.push(this.fb.group({
                delivery_number: item.delivery_number,
                id: item.sales_delivery_id,
                details: this.fb.array([this.patchDetails(item.details, item.details.length-1)])

            }));
        });
  }

  patchDetails(item_details, i) {
        let rows =  (<FormArray>this.myForm.controls['rows']).controls[i]['controls']['details'] as FormArray
        item_details.forEach(item => {
            rows.push(this.fb.group({
                sku: item.ingredient_name
            }));
        });
        console.log(rows)
  }

Solution

  • details: this.fb.array([this.patchDetails(item.details, item.details.length-1)])
    

    You are calling patchDetails while creating the form array, but the method doesn't return anything, instead you can modify patchDetails to return a FormArray, something like this

        patchValues(): void {
            let rows = this.myForm.get('rows') as FormArray;
            this.orders.sales.deliveries.forEach(item => {
                rows.push(this.fb.group({
                    delivery_number: [item.delivery_number],
                    id: [item.sales_delivery_id],
                    details: this.patchDetails(item.details)
                }));
            });
        }
    
    
        patchDetails(item_details: any[]): FormArray {
            let detailsFormArray: FormArray = new FormArray([]);
            item_details.forEach(item => detailsFormArray.push(this.fb.group({
              sku: [item.ingredient_SKU],
              name: [item.ingredient_name]
            })));
            return detailsFormArray;
        }
    

    Stackblitz