反应形式的自定义验证程序控制数量 [英] Custom Validator Control Quantity in Reactive Forms

查看:71
本文介绍了反应形式的自定义验证程序控制数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had a hard time implementing a custom validation in my reactive forms in Angular. I need to control the quantity. The quantity should not be more than the available quantity. The problem how can i get the total of all the quantity if each row has subrows. How will i able to compute the total of subrows and compare it to its parent row where the available quantity is found. Here's my code below.

这也是我的代码的链接请点击此链接

Here's also the link to my code 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
        };
      }
    }
  }

推荐答案

关键是使用父级"到达formArray.那么我们可以使用map来变换数组,只得到que数量,然后减少来获得数量的总和.

the key is using "parent" to reach the formArray. then we can use map to transform the array and get only que quantity and reduce to get the sum of the quantities

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

这篇关于反应形式的自定义验证程序控制数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆