所以下面的代码是在Angular 4中,我不明白为什么它不能按预期的方式工作。

这是我的处理程序的一个片段:

onUpdatingServerName(event: Event) {
  console.log(event);
  this.newserverName = event.target.value; //this wont work
}

HTML元素:

<input type="text" class="form-control" (input)="onUpdatingServerName($event)">

代码给出了错误:

属性“value”在类型“EventTarget”上不存在。

但是在console.log中可以看到,该值确实存在于event.target上。


当前回答

React有一些接口,比如ChangeEvent用于onChange, FormEvent用于onSubmit等

我也试着做类似的事情,下面的解决方案对我有用

handleChange (e : React.ChangeEvent<HTMLInputElement>) {
  console.log(e.currentTarget.value);
}


<input 
   autoFocus
   value={this.state.account.username}
   onChange={this.handleChange}
   id="username" 
   type="text" 
   className="form-control" 
/>

其他回答

声明接口

export interface HTMLInputEvent extends Event {
  target: HTMLInputElement & EventTarget;
}

哪种类型可以作为不同输入事件的类型重用

public onChange(event: HTMLInputEvent) {
  const value = event.target.value;
}

添加任意类型的事件

event: any

例子

[element].addEvenListener('mousemove', (event: any) =>{
//CODE//
} )

发生的事情是typescript将“event”(在这种情况下单击)添加为事件类型,由于某种原因它不识别某些属性。将它添加为any类型不再存在此问题,这适用于任何文档。

你可以显式地将它解析为"HTMLInputElement"然后访问" value "

onUpdatingServerName(event: Event) {
  console.log(event);
  this.newserverName = (<HTMLInputElement>event.target).value; 
}

下面是另一个对我有用的方法:

(事件。target as HTMLInputElement).value

这应该通过让TS知道该事件来消除错误。target是一个HTMLInputElement,它固有地有一个值。在指定之前,TS可能只知道事件本身是一个HTMLInputElement,因此根据TS,输入的目标是一些随机映射的值,可以是任何东西。

这适用于我的ANGULAR HTML组件!!

$any($event.target).value

源链接: https://www.tektutorialshub.com/angular/property-value-does-not-exist-on-type-eventtarget-error-in-angular/