所以下面的代码是在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寻找一个类似的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…
}

其他回答

我正在用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…
}

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

$any($event.target).value

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

要解决这个问题,使用$any类型转换函数($any($event.target).value)来停止模板中的类型检查。

点击这里阅读更多。

请试试这个

<input type = 'text' [value] = 'value' (input) = 'data = $any($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