我在Angular 2组件代码中使用的是TypeScript Version 2。

我得到错误“属性“值”不存在类型“EventTarget”下面的代码,什么可能是解决方案。谢谢!

e.target.value.match(/\S+/g) || []).length

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'text-editor',
  template: `
    <textarea (keyup)="emitWordCount($event)"></textarea>
  `
})
export class TextEditorComponent {
  @Output() countUpdate = new EventEmitter<number>();

  emitWordCount(e: Event) {
    this.countUpdate.emit(
            (e.target.value.match(/\S+/g) || []).length);
  }
}

当前回答

应该使用currentValue,因为currentValue的类型是EventTarget & HTMLInputElement。

其他回答

下面是指定event.target的另一种方法:

import { Component, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'text-editor', template: `<textarea (keyup)="emitWordCount($event)"></textarea>` }) export class TextEditorComponent { @Output() countUpdate = new EventEmitter<number>(); emitWordCount({ target = {} as HTMLTextAreaElement }) { // <- right there this.countUpdate.emit( // using it directly without `event` (target.value.match(/\S+/g) || []).length); } }

不要使用其他答案的变通方法,包括转换事件、事件目标或完全禁用类型检查。这不安全。

相反,您应该从HTML元素中“提取”值,并将其作为参数传递。

非常简单的例子:

<input #searchBox type="text" (input)="doSearch(searchBox.value)">
doSearch(text: string): void {
}

所以如果你把它扩展到原来的例子,你应该得到这个:

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'text-editor',
  template: `
    <textarea #text (keyup)="emitWordCount(text.value)"></textarea>
  `
})
export class TextEditorComponent {
  @Output() countUpdate = new EventEmitter<number>();

  emitWordCount(text: string) {
    this.countUpdate.emit(
      (text.match(/\S+/g) || []).length);
  }
}

角10 +

tsconfig开放。禁用strictDomEventTypes。

  "angularCompilerOptions": {
    ....
    ........
    "strictDomEventTypes": false
  }

由于我以稍微不同的方式搜索了两个问题,我复制了我的答案,以防你在这里结束。

在被调用的函数中,你可以用以下方法定义你的类型:

emitWordCount(event: { target: HTMLInputElement }) {
  this.countUpdate.emit(event.target.value);
}

这假设您只对目标属性感兴趣,这是最常见的情况。如果你需要访问事件的其他属性,一个更全面的解决方案包括使用&类型交集操作符:

event: Event & { target: HTMLInputElement }

你也可以更具体,而不是使用htmllinputelement,你可以使用例如HTMLTextAreaElement的文本区域。

考虑任何美元()

<textarea (keyup)="emitWordCount($any($event))"></textarea>