angular - “typeof Validators”类型上不存在属性“equal”
问题描述
.ts
我在 Angular 12 应用程序的文件中有以下代码:
import { Validators, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
declare module '@angular/forms' {
export namespace Validators {
export let equal: (this: typeof Validators, firstControlName: string, secondControlName: string) => ValidatorFn;
}
}
Validators.equal = function(firstControlName: string, secondControlName: string): ValidatorFn {
return equalValidator(firstControlName, secondControlName);
};
export const equalValidator = (firstControlName: string, secondControlName: string): ValidatorFn => {
return (control: AbstractControl): ValidationErrors | null => {
const firstControl = control.get(firstControlName);
const secondControl = control.get(secondControlName);
if (firstControl && secondControl && firstControl.value !== secondControl.value) {
secondControl.setErrors({ equal: true });
return null;
}
secondControl?.setErrors({ equal: null });
secondControl?.updateValueAndValidity({ onlySelf: true });
return null;
}
}
这在编辑器中显示没有错误,所以我在另一个.ts
文件的组件中使用它,甚至可以自动完成该equal
函数:
Validators.equal('password', 'passwordConfirmation');
但是,当我编译应用程序时,我在上面的行中收到错误:
“typeof Validators”类型上不存在属性“equal”。
我错过了什么?
解决方案
看起来包含验证器的文件已从编译中删除,因为没有引用它的模块。
一个包含它的好地方是main.ts
:
...
import { AppModule } from "./app/app.module";
import "./app/shared/validators.ts";
platformBrowserDynamic().bootstrapModule(AppModule)
...