如何在Angular7中动态添加的formArray中的formcontrol上添加valueChanges?

问题描述 投票:0回答:1

我想在formarray中为formcontrol动态添加valuechanges。

这是我的.ts文件

const pwnhAmountControl = <FormArray>this.PWNHAmountForm.controls['formAwnhamountListObject'];

for (let amountObject of this.PWNHAmountData) {
    pwnhAmountControl.push(this.fb.group(
        {
             CustomerId: [amountObject.CustomerId],
             ProductId: [amountObject.ProductId],
             Period: [amountObject.Period],
             SACId: [amountObject.SACId],
             SACName: [amountObject.SACName],
             AccrualFromDate: this.datePipe.transform([amountObject.AccrualFromDate.substring(0, 10)], "MM/dd/yyyy"),
             AccrualAmount: [amountObject.AccrualAmount],
             UserId: ["support"],
             ProductName: [this.fproductname],
             CustomerName: [this.fcustomername]
         }));
}

我想监听AccrualAmount的数值变化,请帮助我。

angular typescript
1个回答
0
投票

你可以在循环里面为每个索引(控件)做,就像这样。

    for (let i = 0; i < this.PWNHAmountData.length; i++) {
      // build the form 
      pwnhAmountControl.push(this.fb.group(
        {
             CustomerId: [amountObject.CustomerId],
             ProductId: [amountObject.ProductId],
             Period: [amountObject.Period],
             SACId: [amountObject.SACId],
             SACName: [amountObject.SACName],
             AccrualFromDate: 
             this.datePipe.transform([amountObject.AccrualFromDate.substring(0, 10)], 
             "MM/dd/yyyy"),
             AccrualAmount: [amountObject.AccrualAmount],
             UserId: ["support"],
             ProductName: [this.fproductname],
             CustomerName: [this.fcustomername]
         }));
       // listn to values changes
      formArray.at(i).get('AccrualAmount').valueChanges.subscribe(value => {
        console.log('AccrualAmount',value);
        // Here you can set the value back to zero if it's empty
        let numericValue = +value; // convert from string to number
         if(numericValue == 0){ // see if the result is equal to zero
          formArray.at(i).get('age').setValue(0,{emitEvent: false}); // set it to look like a zero
         // make sure to use {emitEvent: false} so you don't stuck in a loop of setting the value and then triggering the onValuChange event.
        }
      });
     }

stackblitz再现。这是一个不同的例子,但它有相同的情况)。

https:/stackblitz.comeditangular-szxkme-t2aahm?file=appautocomplete-display-example.ts。

你可以在第49行找到所需的代码。如果确实对你有帮助,请将答案标记为正确。

© www.soinside.com 2019 - 2024. All rights reserved.