如何在Angular 5反应性表单中将表单控制值传递给自定义验证函数的参数

时间:2018-12-13 20:29:05

标签: angular typescript angular-reactive-forms

analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false
linter:
  // usual stuff

我在浏览器中收到错误:this.FormGroupName = this.formBuilder.group({ reason: ['', Validators.compose([Validators.required])], category: ['', Validators.compose([Validators.required, this.checkCategoryInput(this.whatHappenedFormGroup.controls.category.value, this.categoryList)])] });

我猜我必须检查类别控制值是否为null。我尝试在函数中执行此操作,但似乎需要更早完成。

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

1 个答案:

答案 0 :(得分:2)

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

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