所以下面的代码是在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上。


当前回答

在模板中-

`(keyup)="value2=$any($event.target).value"`

在组件中-

getInput(event: Event) {
  this.value1 = (event.target as HTMLInputElement).value;
}

其他回答

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

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

将HTMLInputElement作为泛型传递给事件类型也可以工作:

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

声明接口

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

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

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

请试试这个

<input type = 'text' [value] = 'value' (input) = 'data = $any($event.target).value'>

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

(事件。target as HTMLInputElement).value

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