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

当前回答

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

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

其他回答

fromEvent<KeyboardEvent>(document.querySelector('#searcha') as HTMLInputElement , 'keyup')
    .pipe(
      debounceTime(500),
      distinctUntilChanged(),
      map(e  => {
            return e.target['value']; // <-- target does not exist on {}
        })
    ).subscribe(k => console.log(k));

也许上面的方法会有所帮助。 根据实际代码更改它。 问题是........目标(“价值”)

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

最好的方法是使用template =>添加id到您的输入,然后使用它的值

<输入类型=“文本”“了解更多”>

searchNotary(value: string) {
 // your logic
}

这样,当严格验证被激活时,你将永远不会出现Typescript错误=>参见angular Docs

用户TypeScript内置在实用程序类型Partial< type >中

在模板中

(keyup)="emitWordCount($event.target)"

在你的组件中

 emitWordCount(target: Partial<HTMLTextAreaElement>) {
    this.countUpdate.emit(target.value./*...*/);
  }

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