如何根据 angular 5 反应形式的 List 验证 FormControl 值

mas*_*su9 3 angular-material angular angular-reactive-forms

是否可以使用自定义验证器将表单字段的输入与列表进行比较?我不想将两个表单控件相互比较。

我一直在尝试这种方法:

this.formGroupName = this.formBuilder.group({
    category: ['', Validators.compose([Validators.required, this.checkCategoryInput(
      this.formGroupName.get['category'].value, this.categoryList)])]
});
Run Code Online (Sandbox Code Playgroud)

在该checkCategoryInput()方法中,我将“类别”表单控件的值与可接受类别列表进行比较。

public checkCategoryInput(input: string, categoryList: any[]): {[key: string]: boolean} | null{
  console.log(input);
  console.log(categoryList);
  return null;
}
Run Code Online (Sandbox Code Playgroud)

但是,我在语法中迷失了方向,并在尝试使用这种方法时遇到了一些错误。有没有人有更好的方法将表单控件值与列表进行比较???

joh*_*667 5

你很接近,你是对的;语法有点混乱。自定义Validator应该是一个ValidatorFn将使用参数调用的方法AbstractControl。例如,这是一个非常基本的验证器:

public static numeric(control: AbstractControl): { [key: string]: any } {
    return /^[0-9]+$/.test(control.value) ? null : { 'numeric': false };
}

// .. { category: [0, Validators.required, numeric] }
Run Code Online (Sandbox Code Playgroud)

我们只是将方法的引用传递给FormBuilder,它会调用传递FormControl它来验证值。

如果你想用验证器包装一些你自己的参数,只需创建你自己的函数范围并返回一个新方法:

public static checkCategoryInput(input: string, categoryList: any[]): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        const val = control.value;
        return 'Do stuff with the value because `input` and `categoryList` are now in scope!'
    }
}
Run Code Online (Sandbox Code Playgroud)

就像一些额外的信息,因为它也没有在任何地方得到很好的说明;的返回签名{ [key: string]: boolean } | null是将放在 的errors属性上的内容ngControl,因此通常您null在有效和errorName: false无效时返回。如果您尝试显示基于此特定验证器的错误消息,请记住这一点。