以反应形式动态生成的复选框的自定义验证器不起作用

Custom validator for dynamically generated checkbox in reactive form is not working

我在 Angular 13 版本中创建了一个项目来验证动态生成的复选框。我关注了这个博客 (https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular)。在这个博客中,有一个自定义验证。但是验证对我不起作用。自定义验证器代码为:

function minSelectedCheckboxes(min = 1) {
    const myValidator: ValidatorFn = (formArray: FormArray) => {
        const totalSelected = formArray.controls
            .map(control => control.value)
            .reduce((prev, next) => next ? prev + next : prev, 0);
        return totalSelected >= min ? null : { required: true };
    };

    return myValidator;
}

但我收到以下错误。谁能帮我解决这个错误?

src/app/app.component.ts:62:8 - error TS2322: Type '(formArray: FormArray) => { required: boolean; } | null' is not assignable to type 'ValidatorFn'. Types of parameters 'formArray' and 'control' are incompatible. Type 'AbstractControl' is missing the following properties from type 'FormArray': controls, at, push, insert, and 6 more.

62 const myValidator: ValidatorFn = (formArray: FormArray) => { ~~~~~~~~~~~

ValidatorFn 具有以下类型:

export declare interface ValidatorFn {
    (control: AbstractControl): ValidationErrors | null;
}

所以你需要像这样更改函数:

function minSelectedCheckboxes(min = 1) {
  const myValidator: ValidatorFn = (control: AbstractControl) => {
    const formArray = control as FormArray;
    const totalSelected = formArray.controls
      .map((control) => control.value)
      .reduce((prev, next) => (next ? prev + next : prev), 0);
    return totalSelected >= min ? null : { required: true };
  };

  return myValidator;
}