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


当前回答

如你所知,TypeScript一直严格遵循元素数据类型。因此,如果不指定元素的数据类型,就不能直接访问元素的属性。该事件。target是一个HTMLElement,它是所有HTML元素的父元素,但不保证有属性值。

因此,我们需要对变量event进行类型转换。目标,那么只有我们可以从它访问value属性。

OnUpdatingServerName (event: Event) {
  console.log(event);
  var element = event.target as HTMLElement
  this.newserverName = element.value;
}

其他回答

试试下面的代码:

  console.log(event['target'].value)

这对我有用:-)

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

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

请试试这个

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

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

$any($event.target).value

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

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

(事件。target as HTMLInputElement).value

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