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

标签 angular typescript visual-studio-code

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

this.format = document.querySelector('input[name="case"]:checked').value;

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

所以有人能看出我为什么会收到此错误吗?谢谢你的帮助。如果您需要更多信息,请告诉我。

'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'

这是指令:

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

和 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'">

最佳答案

这是 typescript 错误。默认情况下 document.querySelector 返回没有输入值的 Element 实例。

你必须“施放”它:

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

关于angular - 类型元素上不存在单选按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48700706/

相关文章:

angular - 关闭前一个后,一个一个地打开几个mat-dialogs

angular - 如何修复 Angular 6 中的 'Google Maps JavaScript API error: InvalidKeyMapError' 错误?

reactjs - Jest : test suite failed to run Error: No message was provided

javascript - 安装 eslint 作为扩展和安装为 npm 包有什么区别?

javascript - 如何基于 rxjs 中现有的 observable 创建一个新的 observable 订阅?

angular - 如何在 Protractor 中正确链接 promise

javascript - 如何从 VSCode 扩展执行本地 bash 代码

typescript - "export as namespace foo"的目的是什么?

c++ - 如何让 VS Code 识别 'constexpr' ?

javascript - 在 Mac 上的 VSCode 中调试 Javascript