Custom Validator Control Quantity in Reactive Forms

前端 未结 1 1424
后悔当初
后悔当初 2021-01-16 02:22

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 quanti

相关标签:
1条回答
  • 2021-01-16 02:57

    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
              };
            }
          }
        }
      }
    
    0 讨论(0)
提交回复
热议问题