Custom Validator Control Quantity in Reactive Forms

对着背影说爱祢 提交于 2019-12-20 05:43:09

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/52026735/custom-validator-control-quantity-in-reactive-forms

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