首页 文章

反应表单中的自定义验证器控制数量

提问于
浏览
2

我很难在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

    关键是使用“parent”来到达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
              };
            }
          }
        }
      }
    

相关问题