首页 > 解决方案 > 计算变化时所有角度反应输入的总量

问题描述

我有反应形式,只有多个数字输入。我使用函数来修改更改时的每个输入值:

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

此控制台记录更改后每个输入的修改值,但我需要控制台记录所有输入的总量。我怎样才能做到这一点?

标签: angulartypescriptangular-reactive-forms

解决方案


我应该使用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);
    })
  }

推荐阅读