Set Value Not Less Than 0 In FormArray Reactive Fo

2019-08-02 04:09发布

问题:

I have successfully implemented the value in the input field to not less than 1 in the "quantityControl" formControlName. However my problem is when on the formArray. How can i set that to not than less than 0 or should not be a negative number?

Here's the code below and the link to my stackblitz CODE LINK

this.inquiryForm.get('quantityControl').valueChanges.pipe(
          filter(quantity => quantity < 1)
    ).subscribe(value => {
      console.log(value);

      this.inquiryForm.get('quantityControl').setValue(1);
    });

回答1:

For better understanding of Form check here.

Use compose() to configure your Input field with multiple custom validations.

this.form = formBuilder.group({
        formControlNameValue:['', Validators.compose([Validators.required, positiveVal ])
        ]});

and implement positiveVal

static positiveVal(control:Control):{ [key: string]: any; } {
  if (Number(control.value) < 0) {
    return {nonZero: true};
  } else {
    return null;
  }
}