代码之家  ›  专栏  ›  技术社区  ›  Vladimir Humeniuk

计算所有角度无功输入的总变化量

  •  0
  • Vladimir Humeniuk  · 技术社区  · 7 年前

    initsForm() {
      this.form = this.fb.group({
                    coffee: ['0', [
                     Validators.min(0)
                    ]],
                    tea: ['0', [
                     Validators.min(0)
                   ]]
                  })
    
      this.countAmount();
    }
    
    
    
    countAmount() {
          this.form.valueChanges.subscribe(val => {
              Object.keys(this.form.controls).forEach(key => {
              console.log((this.form.get(key).value * 1.75))
            })
          })
        }
    

    此控制台日志修改了每个输入值后的更改,但我需要控制台日志中所有输入的总数。我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Vladimir Humeniuk    7 年前

    我应该用 reduce 方法:

      countAmount() {
        this.form.valueChanges.subscribe(val => {
          let res = [];
    
          Object.keys(this.form.controls).forEach(key => {
            res.push(this.form.get(key).value * this.counters[key])
          });
    
          res = res.reduce((prev, next) => prev + next);
    
          this.totalAmount += Number(res);
        })
      }
    
    推荐文章