找不到路径如下的控件:“ purchaseOrderProducts->(0,1 ..)-> unitTotalPrice”,并且无法读取null的属性“ setValue”

时间:2019-08-07 10:30:49

标签: angular angular6 angular5 angular7 angular8

API的值

    {
       "referenceNumber": "PO1",
       "purchaseOrderProducts": [
        {
          "productId": "a1a1a1",
          "quantity": 10,
          "ratePerUnit": 10
        },
        {
          "productId": "b1b1b1",
          "quantity": 10,
          "ratePerUnit": 123.11
        },
        {
           "productId": "c1c1",
           "quantity": 10,
           "ratePerUnit": 12345.11
        }
     ]}

我必须在表中显示PurchaseOrderProducts []:formArray

要计算,

         unitTotalPrice= quantity * ratePerUnit

为此,我使用以下stackblitz示例作为参考      https://stackblitz.com/edit/angular-reactive-form-sobsoft  使用以下代码进行计算

private updateTotalUnitPrice(purchaseOrderProducts: any) {
const control = <FormArray>this.PurchaseOrderFormGroup.controls['purchaseOrderProducts'];
for (let i in purchaseOrderProducts) {
  this.totalUnitPrice = (purchaseOrderProducts[i].quantity * purchaseOrderProducts[i].ratePerUnit);
  let totalUnitPriceFormatted = this.currencyPipe.transform(this.totalUnitPrice, 'USD', 'symbol-narrow', '1.2-2');
  control.at(+i).get('unitTotalPrice').setValue(totalUnitPriceFormatted, { onlySelf: true, emitEvent: false });
}}

并声明formArray

    initPOProducts() {
       const numberPatern = '^[0-9.,]+$';
       return this.fb.group({
          productId: [null, [Validators.required]],
          quantity: [1, [Validators.required]],
          unitTotalPrice: [{ value: '', disabled: true }],
          ratePerUnit: ['', [Validators.pattern(numberPatern), Validators.pattern(numberPatern)]],
     })
   }

并在init()之后使用

this.myFormValueChanges = this.PurchaseOrderFormGroup.controls['purchaseOrderProducts'].valueChanges;
       this.myFormValueChanges.subscribe(purchaseOrderProducts => 
this.updateTotalUnitPrice(purchaseOrderProducts));

受影响的问题

但是,当我使用此方法时,仅会获取purchaseOrderProducts数组的index [0]值。

所以我使用以下方法获取所有purchaseOrderProducts值

   bindproducts(products: purchaseOrderProduct[]): FormArray {
        const productFormArray = new FormArray([]);
        products.forEach(product => {
           productFormArray.push(
               this.fb.group({
                  productId: product.productId,
                  quantity: product.quantity,
                  ratePerUnit: product.ratePerUnit
            }));
       });return productFormArray;}

并用于价值获取方法

   this.PurchaseOrderFormGroup.setControl('purchaseOrderProducts', this.bindproducts(PurchaseOrder.purchaseOrderProducts));

因此,该问题已解决。

现在

unitTotalPrice 无法计算。出现两个错误,

      1. ERROR TypeError: Cannot read property 'setValue' of null
      2.ERROR Error: Cannot find control with path: 'purchaseOrderProducts -> (0,1...) -> unitTotalPrice'

有人可以帮助我吗?

0 个答案:

没有答案