反应形式的自定义验证程序控制数量

时间:2018-08-26 13:31:05

标签: angular angular-reactive-forms angular-forms angular-validation angular-validator

我很难在Angular中以我的反应形式实现自定义验证。我需要控制数量。该数量不应超过可用数量。问题是,如果每一行都有子行,我如何获得所有数量的总数。我将如何计算子行的总数,并将其与找到可用数量的父行进行比较。这是下面的代码。

这也是我的代码PLEASE CLICK THIS LINK

的链接
customValidator(campo1: string) {
    return (group: FormGroup): { [key: string]: any } => {
      const receive = group.controls[campo1];
       //Change this
      const available = 10;
      if (receive.value > available) {
        return {
          out: true
        };
      }
    }
  }

1 个答案:

答案 0 :(得分:0)

关键是使用“父级”到达formArray。那么我们可以用map变换数组,只得到que数量,然后减少来求和。

customValidator(campo1: string) {
    return (group: FormGroup): { [key: string]: any } => {
      //get the formArray
      const form=(group.parent as FormArray);
      if (form)
      {
        //get the available quantity using parent
        let available =form.parent.get('available_quantity').value;

        //the final available are the available less each quantity
        available=form.value //In form.value we have e.g. [{quantity:10..},{quantity:16}]
          .map(x=>x.quantity?+x.quantity:0)  //using map we have, e.g. [10,16]
          .reduce((a, b) => a - b, available)  //using reduce we substract the quantities to available
        if (available<0) {
          return {
            out: true
          };
        }
      }
    }
  }
相关问题