【问题标题】:How to compare two values in formBuilder?如何比较formBuilder中的两个值?
【发布时间】:2020-01-15 19:48:37
【问题描述】:

我的表单生成器如下,

this.feedbackForm = new FormGroup({
  figure: new FormControl('', Validators.pattern(/^[0-9]+$/)),
  maxVal: new FormControl(''),
  minVal: new FormControl('', Validators.max(feedbackForm.values.maxVal - 1)),
});

我想比较 minVal 使其小于最大值,但是从上面的代码中它显示的错误如下,

错误类型错误:无法读取未定义的属性“值”

【问题讨论】:

    标签: javascript html angular mean-stack angular-reactive-forms


    【解决方案1】:

    您在表单定义中引用了您的表单。这意味着您在定义之前引用了feedbackForm

    有很多方法可以实现您的目标。一种方法是在定义表单后将验证器添加到表单控件。

    this.feedbackForm = new FormGroup({
      figure: new FormControl('', Validators.pattern(/^[0-9]+$/)),
      mixVal: new FormControl(''),
      maxVal: new FormControl('', Validators.pattern(/^[0-9]+$/)),
    });
    
    
    this.feedbackForm.get('minVal')
        .setValidators(Validators.max(this.feedbackForm.get('maxVal').value - 1))
    

    【讨论】:

      【解决方案2】:

      marcusshep 提到有几种可能的方法,并提供了一种很好的方法。我想我会添加另一个。不过,对于您想要的东西,这可能有点过头了。

      您可以将其设为表单级别的自定义验证器。

      static minLessThanMax(control: AbstractControl): ValidationErrors {
          const value: formValue = (control as FormGroup).getRawValue();
          if (value) {
              const minValue = formValue.minValue;
              const maxValue = formValue.maxValue;
      
              if (minValue > maxValue) {
                  control.get('min').setErrors({ minMoreThanMax: true });
              } else {
                  control.get('end').setErrors(null);
              }
          }
          return null;
      }
      

      然后当您新建 FormGroup 时:

      this.feedbackForm = new FormGroup({
        figure: new FormControl('', Validators.pattern(/^[0-9]+$/)),
        mixVal: new FormControl(''),
        maxVal: new FormControl('', Validators.pattern(/^[0-9]+$/)),
      }, { validator: minLessThanMax });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-20
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多