【问题标题】:Angular - Type '(c: FormControl) => ValidationError | null' is not assignable to type 'ValidatorFn'Angular - 类型 \'(c: FormControl) => ValidationError | null\' 不可分配给类型 \'ValidatorFn\'
【发布时间】:2023-01-31 10:21:58
【问题描述】:

在 Angular-13 中我有这段代码

验证-errors.ts:

import { ValidationErrors } from "@angular/forms";
import { FormArray, FormControl, FormGroup, ValidatorFn } from '@angular/forms';

// Defines a stronger typed validation error model, compatible with the Angular default.
export interface ValidationError extends ValidationErrors {
    [validatorName: string]: {
        message: string
    }
}

验证.component.ts :

import { ValidationError } from '../models/validation-error';

export class CustomValidators {
  static requiredMinNumber(min: number): ValidatorFn {
    return (c: FormControl): ValidationError | null => {
      if (this.isEmpty(c.value))
        return this.makeError('requiredMinNumber', `You must provide a number of at least ${min}.`);
      else if (!this.isNumber(c.value))
        return this.makeError('requiredMinNumber', `Value must be a number, and minimum ${min}.`);
      else if (c.value < min)
        return this.makeError('requiredMinNumber', `The minimum accepted value is ${min}.`);
      return null;
    };
  }
}

但是出现了这个错误:

Type '(c: FormControl) => ValidationError | null' is not assignable to type 'ValidatorFn'.
  Types of parameters 'c' and 'control' are incompatible.
    Type 'AbstractControl' is not assignable to type 'FormControl'.ts(

我该如何解决?

谢谢

【问题讨论】:

    标签: angular typescript angular-reactive-forms angular-custom-validators


    【解决方案1】:

    要编写自定义验证器,必须关注ValidationFn interface

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

    c 更改为 AbstractControl 类型。

    static requiredMinNumber(min: number): ValidatorFn {
      return (c: AbstractControl): ValidationError | null => {
        ...
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 2023-01-25
      • 2021-08-22
      • 2020-08-29
      • 2018-07-07
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多