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


当前回答

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

$any($event.target).value

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

其他回答

在模板中-

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

在组件中-

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

声明接口

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

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

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

你应该使用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

我正在用React寻找一个类似的TypeScript错误的解决方案:

在TypeScript中的EventTarget类型上不存在属性'dataset'

我想在React中获取一个点击按钮元素的event.target.dataset:

<button
  onClick={onClickHandler}
  data-index="4"
  data-name="Foo Bar"
>
  Delete Candidate
</button>

下面是我如何通过TypeScript获得数据集值“存在”:

const onClickHandler = (event: React.MouseEvent<HTMLButtonElement>) => {
  const { name, index } = (event.target as HTMLButtonElement).dataset
  console.log({ name, index })
  // do stuff with name and index…
}

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

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