运行 并根据 angular 表单 builder/group 中其他字段的值设置一个字段的验证错误

Run and set the validation errors on one field based on the value of other field in angular form builder/group

我希望自定义函数验证器 运行 模糊 StartDate 和 EndDate

component.ts

Createform(){
this.studentForm = formBuilder.group({
      StartDate: ['', Validators.required, customFunction(), updateOn: "blur" ],
      EndDate: ['', null,customFunction(), updateOn: "blur" ],

}

自定义函数

customFunction(){
 if (EndDate <= startDate) {
          return of({ invalidDate: true });
        } 
      }  
      return of(null);
    };
}

它在 运行 开始日期时将 CreateForm.controls['StartDate'].errors?.invalidDate 设置为 true。是否可以在 EndDate 上设置此 invalidDate,即使我 运行 StartDate 上的函数?

自定义函数 运行 正确,但是当它 运行 在 StartDate 时,它​​会在开始日期设置错误数组,但我希望在 EndDate 设置错误,这可能吗?

在您的自定义函数中,您可以使用 setErrors 函数在不同的字段上设置错误

自定义函数

customFunction(){
 if (EndDate <= startDate) {
         this.studentForm.form.controls['endDate'].setErrors({'invalidDate': true});;
        } 
      }  
      return of(null);
    };
}