我在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);
  }
}

当前回答

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

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

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

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

event: Event & { target: HTMLInputElement }

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

其他回答

你需要显式地告诉TypeScript你的目标HTMLElement的类型。

方法是使用泛型类型将其转换为合适的类型:

this.countUpdate.emit((<HTMLTextAreaElement>e.target).value./*...*/)

或者(随你)

this.countUpdate.emit((e.target as HTMLTextAreaElement).value./*...*/)

或者(还是偏好问题)

const target = e.target as HTMLTextAreaElement;

this.countUpdate.emit(target.value./*...*/)

这将让TypeScript知道元素是一个文本区域,它将知道value属性。

同样的事情也可以用在任何HTML元素上,只要你给TypeScript更多关于它们类型的信息,它就会给你适当的提示,当然错误也会更少。

为了便于以后使用,你可以直接用目标的类型定义一个事件:

// create a new type HTMLElementEvent that has a target of type you pass
// type T must be a HTMLElement (e.g. HTMLTextAreaElement extends HTMLElement)
type HTMLElementEvent<T extends HTMLElement> = Event & {
  target: T; 
  // probably you might want to add the currentTarget as well
  // currentTarget: T;
}

// use it instead of Event
let e: HTMLElementEvent<HTMLTextAreaElement>;

console.log(e.target.value);

// or in the context of the given example
emitWordCount(e: HTMLElementEvent<HTMLTextAreaElement>) {
  this.countUpdate.emit(e.target.value);
}

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

我相信它一定会起作用,但我不知道具体是怎么回事。 另一种方法是,

<textarea (keyup)="emitWordCount(myModel)" [(ngModel)]="myModel"></textarea>


export class TextEditorComponent {
   @Output() countUpdate = new EventEmitter<number>();

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

心理图像11 +。

tsconfig开放。禁用strictTemplates。

 "angularCompilerOptions": {
    ....
    ........
    "strictTemplates": false
  }

下面是指定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); } }