angular - Angular 11 - 类型 '(controlArray: FormArray) => ValidationErrors | null' 不可分配给类型 'ValidatorFn'
问题描述
我尝试在 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
}
}
}
}
}
调用类
constructor(private fb: FormBuilder){}
private buildAuthorsArray(values: string[]): FormArray{
// BookValidators.atLeastOneAuthor is now underlined with the error.
return this.fb.array(values, BookValidators.atLeastOneAuthor);
}
解决方案
很好的答案,但我必须对其进行一些修改才能使其正常工作。这是我的解决方案:
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 }
}
}
}
}