簡體   English   中英

元素引用<any> .nativeElement:任何拋出“任何類型值的不安全調用”錯誤</any>

[英]ElementRef<any>.nativeElement: any throwing "Unsafe call of an any typed value" error

我有以下指令阻止任何字母數字字符輸入到字段中。

在 validateFields 方法中,ESLint 拋出以下錯誤消息:

ESLint:任何類型值的不安全調用。(@typescript-eslint/no-unsafe-call)

我查看了 ElementRef 的類型,它具有以下屬性:

ElementRef<any>.nativeElement: any

考慮到這一點,我該如何解決以下問題。

@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);
  }
}

您需要聲明nativeElement的類型。 由於ElementRef接受一個類型(這將是nativeElement的類型),因此最好的方法是像這樣注入:

private elementRef: ElementRef<HTMLElement>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM