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


当前回答

你应该使用event.target.value prop和onChange处理程序,如果没有,你可以看到:

index.js:1437 Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

或者如果你想使用其他处理程序而不是onChange,使用event.currentTarget.value

其他回答

事件。target在这里是一个HTMLElement,它是所有HTML元素的父元素,但不保证有属性值。TypeScript检测到并抛出错误。事件。目标到适当的HTML元素,以确保它是HTMLInputElement,它有一个value属性:

(event.target as HTMLInputElement).value

根据文档:

输入$event 上面的例子将$event转换为任意类型。这以一定的代价简化了代码。没有类型信息可以揭示事件对象的属性并防止愚蠢的错误。 […] $event现在是一个特定的KeyboardEvent。并非所有元素都具有value属性,因此它将target转换为输入元素。

(强调我的)

您也可以创建自己的界面。

    export interface UserEvent {
      target: HTMLInputElement;
    }

       ...

    onUpdatingServerName(event: UserEvent) {
      .....
    }

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

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

添加任意类型的事件

event: any

例子

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

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

你应该使用event.target.value prop和onChange处理程序,如果没有,你可以看到:

index.js:1437 Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

或者如果你想使用其他处理程序而不是onChange,使用event.currentTarget.value