Custom Validator Control Quantity in Reactive Forms

 ̄綄美尐妖づ 提交于 2019-12-02 06:46:24

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
          };
        }
      }
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!