单选按钮值在类型元素上不存在

imn*_*ghn 1 typescript visual-studio-code angular

嗨,我只是想从我正在处理的 Angular 项目中的组件上的几个单选按钮中获取值。如果我放了相同的违规代码..

this.format = document.querySelector('input[name="case"]:checked').value;
Run Code Online (Sandbox Code Playgroud)

...在控制台日志中的 if 语句中,它不会引发错误。此外,当我重新加载 vs 代码时,有时也不会抛出错误并且它运行良好。

那么有人能明白为什么我会收到这个错误吗?谢谢你的帮助。如果您需要更多信息,请告诉我。

'file:////src/app/input-format2.directive.ts'
severity: 'Error'
message: 'Property 'value' does not exist on type 'Element'.'
at: '15,72'
source: 'ts'
code: '2339'
Run Code Online (Sandbox Code Playgroud)

这是指令:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appInputFormat2]'
})
export class InputFormat2Directive {
  // tslint:disable-next-line:no-input-rename
  @Input('appInputFormat2') format;

  constructor(private el: ElementRef) {}

  @HostListener('blur')
  onBlur() {
    const value: string = this.el.nativeElement.value;
    this.format = document.querySelector('input[name="case"]:checked').value;
    if (this.format === 'lowercase') {
      this.el.nativeElement.value = value.toLowerCase();
    } else {
      this.el.nativeElement.value = value.toUpperCase();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

和 html:

  Custom directive where case is determined by user
  <b>upon loss of focus</b> (clean approach):
</div>
<input type="radio" name='case' value="lowercase">lowercase
<br>
<input type="radio" name='case' value="uppercase">UPPERCASE
<br>
<input type="text" submit="submit" [appInputFormat2]="'lowercase'">
Run Code Online (Sandbox Code Playgroud)

Pie*_*let 5

它是一个打字稿错误。默认情况下 document.querySelector 返回没有输入值的 Element 实例。

你必须“投射”它:

this.format = (<HTMLInputElement>document.querySelector('input[name="case"]:checked')).value;
Run Code Online (Sandbox Code Playgroud)