如何在 Angular 5 响应式表单中将表单控件值传递给自定义验证器函数的参数

How to pass Form Control value to custom Validator Function's Parameter in Angular 5 Reactive Forms

this.FormGroupName = this.formBuilder.group({
  reason: ['', Validators.compose([Validators.required])],
  category: ['', Validators.compose([Validators.required, this.checkCategoryInput(this.whatHappenedFormGroup.controls.category.value, this.categoryList)])]
});

我在浏览器中收到错误:Uncaught (in promise): TypeError: Cannot read property 'controls' of undefined

我猜我必须检查类别控制值是否为空。我尝试在函数中这样做,但似乎需要更早地完成。

有人对如何将类别值传递到我的函数有建议吗?

您必须将它包装在一个包含箭头函数的私有表单字段中,否则它会在组件创建时执行,而不是验证:

export class CategoryFormComponent {
  private categoryValidator = (control: AbstractControl) => {
    return this.checkCategoryInput(control.value, this.categoryList);
  };


  this.whatHappenedFormGroup = this.formBuilder.group({
    reason: ['', Validators.compose([Validators.required])],
    category: ['', Validators.compose([
      Validators.required, 
      this.categoryValidator
    ])]
  });
}