使用Angular中的反应形式在数组内部修补数组

时间:2018-07-09 13:33:37

标签: angular angular-reactive-forms angular-forms reactive-forms formarray

我正在尝试在details FormArray内显示rows FormArray。我无法显示details FormArray的数据,因此需要帮助。我只知道如何显示rows FormArray,但是details FormArray对我来说却很困难。这是我在下面尝试过的。 请参阅我创建的该STACKBLITZ文件。

CLICK THIS LINK

谢谢。

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

1 个答案:

答案 0 :(得分:0)

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

您在创建表单数组时正在调用patchDetails,但是该方法不返回任何内容,而是可以修改patchDetails以返回FormArray,类似这样

    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