Angular 11 - 类型 '(controlArray: FormArray) => ValidationErrors | null' 不可分配给类型 'ValidatorFn'

Geo*_*ris 1 validation angular

我尝试在 Angular 11 中实现验证器,但出现编译错误: Type '(controlArray: FormArray) => ValidationErrors | null' is not assignable to type 'ValidatorFn'.任何想法如何修复此错误?

验证器类:

import { FormArray, ValidationErrors } from "@angular/forms";

export class BookValidators {
    static atLeastOneAuthor(controlArray: FormArray): ValidationErrors | null {
        if(controlArray.controls.some(el => el.value)){
            return null;
        }else{
            return{
                atLeastOneAuthor: {
                    valid: false
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

调用类

constructor(private fb: FormBuilder){}

private buildAuthorsArray(values: string[]): FormArray{
    // BookValidators.atLeastOneAuthor is now underlined with the error.
    return this.fb.array(values, BookValidators.atLeastOneAuthor);
}
Run Code Online (Sandbox Code Playgroud)

小智 7

很好的答案,但我必须对其进行一些修改才能使其正常工作。这是我的解决方案:

  static atLeastOneAuthor(): ValidatorFn {
    return (control: AbstractControl) => {
      const controlArray = control as FormArray;
      if (controlArray.controls.some(el => el.value)) {
        return null;
      } else {
        return {
          atLeastOneAuthor: { valid: false }
        }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • 事实上,这就是“正确”的解决方案。我不明白为什么我们必须首先将参数输入为“control”,然后将其转换为“group”或“array”,以供您的示例使用......我想我必须更深入地研究API: ) (2认同)