在 Angular-13 我有這個代碼
驗證錯誤.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(
我該如何解決?
謝謝
uj5u.com熱心網友回復:
要撰寫自定義驗證器,您必須遵循ValidationFninterface。
interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null
}
更改c為AbstractControl型別。
static requiredMinNumber(min: number): ValidatorFn {
return (c: AbstractControl): ValidationError | null => {
...
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450141.html
上一篇:Angular-元素隱式具有“任何”型別,因為“字串”型別的運算式不能用于索引型別
下一篇:在div之后得到不需要的逗號
