使用 Angular FormArray 计算的值 [英] Calculated values using Angular FormArray

查看:21
本文介绍了使用 Angular FormArray 计算的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据 FormArray 中的特定值计算总数或其他值.

I'm attempting to calculate a total or other value based on a particular value in a FormArray.

我发现当订阅 valueChanges 并尝试将整个数组传递给诸如 reduce 之类的东西时,父级上不存在新值"表单组.

I'm finding that when subscribing to valueChanges and attempting to pass the whole array to something like reduce, the "new value" isn't present on the parent FormGroup.

StackBlitz 上的原始示例

示例:

this.frm.get('arr')['controls'][i].valueChanges
  .subscribe((newVal) => {
    this.frm.get('total').patchValue(
      this.frm.get('arr').value.reduce((acc, curr) => {
        return acc + curr.v;
      }, 0)
    )
  });

如果 arr 的值为 [0, 1, 2, 3, 4] 并且我将第一个值更改为 1,我仍然得到 10 而不是 11.

If arr has values [0, 1, 2, 3, 4] and I change the first value to 1, I still get 10 instead of 11.

this.frm.get('arr').value 显示所有初始值而不是更新值.

this.frm.get('arr').value shows all the initial values and not the updated values.

我对 Reactive Forms 还很陌生,所以我确定我只是在这里遗漏了一些基本的东西.

I'm fairly new to Reactive Forms so I'm sure I'm just missing something fundamental here.

UPDATE(有解决方案,但我仍然缺乏理解):

UPDATE (Have a solution, but I'm still lacking understanding):

我真的很想知道为什么我不能像 Eliseo 建议的那样订阅对整个数组的更改.

I'd really love to know why I'm not able to subscribe to changes to the whole array like Eliseo had suggested.

我也对为什么我使用 .value 的地方之间存在如此大的差异感兴趣 - 如果响应式表单的全部点是模型驱动然后传递 frm.value 到您的 Submit 函数,那么为什么 .value 在整个表单层次结构中如此不一致?

I'm also interested in why there is such a difference between where I use .value - If the whole point of Reactive Forms are to be Model Driven and then pass frm.value to your Submit function, then why is .value so inconsistent throughout the form hierarchy?

更新 2

更新的 StackBlitz 解决方案在 Eliseo 更新后的指导下

我找到了一个让我感觉很好的解决方案.它不会在任何地方使用 controls 并且感觉非常干净.Eliseo 建议的方法促使我尝试一下.我相信重要的是投射到 FormArray 并在其上执行任何 push .这使 parent 字段与 FormGroupFormArray 的其余部分相关联,因此它保持包含在 valueChanges 事件中.

I've found a solution that I feel pretty good about. It doesn't use controls anywhere and feels very clean. Eliseo's suggested approach pushed me to try this out. I believe the important thing is casting to a FormArray and executing any push on that. This keeps the parent field tied to the rest of your FormGroup or FormArray thus it stays included in the valueChanges event.

我现在相信使用 controls 是 Angular Reactive Forms 的反模式,但我需要寻找有关该主题的更多指导.

I now believe using controls is an anti-pattern to Angular Reactive Forms, but I need to search for more guidance on that topic.

推荐答案

为什么不监听所有数组的变化并用 newValues 求和?

why not listen changes of all array and make total with newValues?

 //NOT ['controls'][i]
this.frm.get('arr')['controls'].valueChanges
  .subscribe((newVal) => {
    this.frm.get('total').patchValue(
      //use newVal
      newVal.reduce((acc, curr) => {
        return acc + curr.v;
      }, 0)
    )
  });

那不行,为此修改buildForm的代码:

That's not work, Change the code of buildForm for this:

buildForm() {
    let controls:any[]=[];
    for (let i:number = 0; i < 5; ++i) {
      controls.push(this.builder.group({
        v: i
      }))
    this.frm = this.builder.group({
      total: [{value: '', disabled: true}],
      arr: this.builder.array(controls)
    });
      this.frm.get('arr').valueChanges
      .subscribe((newVal) => {
        let total:number=0;
        newVal.forEach(e=>{
          total=total+parseInt(e.v)});

        this.frm.get('total').patchValue(total,0)

      });
    }
  }

主要变化是使用forEach而不是reduce,使用parseInt,以及制作formArray的方式.

The main changes is use forEach and not reduce, the use of parseInt, and the way to make the formArray.

这篇关于使用 Angular FormArray 计算的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆