[英]ElementRef<any>.nativeElement: any throwing "Unsafe call of an any typed value" error
I have the following directive which blocks any alphanumeric characters from being entered into a field.我有以下指令阻止任何字母数字字符输入到字段中。
In the validateFields method, ESLint is throwing the following error message:在 validateFields 方法中,ESLint 抛出以下错误消息:
ESLint: Unsafe call of an any typed value.(@typescript-eslint/no-unsafe-call)
ESLint:任何类型值的不安全调用。(@typescript-eslint/no-unsafe-call)
I looked at the type for ElementRef and it has has the following properties:我查看了 ElementRef 的类型,它具有以下属性:
ElementRef<any>.nativeElement: any
With this in mind, how can I go about remediating the issue below.考虑到这一点,我该如何解决以下问题。
@Directive({
selector: '[appBlockNonAlphanumericCharacters]',
})
export class BlockNonAlphanumericCharactersDirective {
@Input() isAlphaNumeric = true;
regex = '^[a-zA-Z0-9_-]*$';
constructor(private elementRef: ElementRef) {}
@HostListener('keypress', ['$event']) onKeyPress(event: KeyboardEvent): boolean {
return new RegExp(this.regex).test(event.key);
}
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent): void {
this.validateFields(event);
}
validateFields(event: KeyboardEvent): void {
setTimeout(() => {
if (this.elementRef.nativeElement) {
// Error thrown here - ESLint: Unsafe member access ['value'] on an any value.(@typescript-eslint/no-unsafe-member-access)
this.elementRef.nativeElement['value'] = this.elementRef.nativeElement['value']
.replace(/[^A-Za-z ]/g, '')
.replace(/\s/g, '') as string;
}
event.preventDefault();
}, 100);
}
}
You need to declare the type of nativeElement
.您需要声明
nativeElement
的类型。 Since ElementRef accepts a type (which will be the type of nativeElement
) the best way to do that is by injecting like this:由于ElementRef接受一个类型(这将是
nativeElement
的类型),因此最好的方法是像这样注入:
private elementRef: ElementRef<HTMLElement>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.