【问题标题】:Custom Validator Control Quantity in Reactive Forms响应式表单中的自定义验证器控制数量
【发布时间】:2019-02-01 05:59:16
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    关键是使用“父”来到达formArray。那么我们可以使用map对数组进行变换,只得到que数量,reduce得到数量之和

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

    【讨论】:

    • 你能减少你的代码吗?我可能不需要这个 const receive = group.controls[campo1];等等……
    • 这些“{ [key: string]: any }”和“campo1: string in customerValidator()”怎么样?我需要放这个吗?谢谢。
    • 没错,在这种情况下它不是必需的,我让它以防万一需要检查值(想象一下,如果你想检查值是否为负)。 {key:string...} 是函数“返回”的类型。所有的评论都是“只建议”代码是可以理解的
    • 你能删除所有不必要的代码吗?谢谢eliseo
    • customValidator() 中的 campo:string 怎么样?我需要那个吗?我不需要那个参数?
    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 2022-01-23
    • 2020-10-16
    • 2018-09-19
    • 2018-07-14
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多