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


当前回答

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

(事件。target as HTMLInputElement).value

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

其他回答

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

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

试试下面的代码:

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

这对我有用:-)

我建议创建一个实用程序类型:

interface MyEvent<T extends EventTarget> extends Omit<Event, 'target'> {
  target: T;
}

然后像这样使用它:

function onChange({ target: { value } }: MyEvent<HTMLInputElement>) => {
  doSomethingWith(value);
}

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

    export interface UserEvent {
      target: HTMLInputElement;
    }

       ...

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

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