我得到一个错误的时候,构建Angular 应用程序.

HTML Template

  <mat-form-field *ngIf="requested">
    <input
      matInput
      (input)="sendingAccesscode($event)"
      placeholder="{{ 'CODE_LABEL' | i18next }}"
      name="accesscode"
      formControlName="accesscode"
      minlength="6"
      required
    />
  </mat-form-field>

TypeScript

  sendingAccesscode(event: { target: { value: string }}) {
    if (event.target?.value.length >= 6) {
      this.accessCode.emit(event.target.value);
    }
  }

我收到以下错误:

error TS2345: 
Argument of type 'Event' is not assignable to parameter of type '{ target: { value: string; }; }'.
  Types of property 'target' are incompatible.
    Type 'EventTarget | null' is not assignable to type '{ value: string; }'.
      Type 'null' is not assignable to type '{ value: string; }'.

13       (input)="sendingAccesscode($event)"
                                    ~~~~~~```

推荐答案

将其设置为类型Event如何?这将解决您的问题!

您也可以使用InputEvent

sendingAccesscode(event: Event) {
    const value = (event.target as HTMLInputElement).value;
    if (value && value.length >= 6) {
      console.log(value);
    }
  }

stackblitz

Javascript相关问答推荐

使用Java脚本根据按下的按钮更改S文本

Javascript json定制

单个HTML中的多个HTML文件

如何将数组用作复合函数参数?

为什么客户端没有收到来自服务器的响应消息?

无法避免UV:flat的插值:非法使用保留字"

删除加载页面时不存在的元素(JavaScript)

从逗号和破折号分隔的给定字符串中查找所有有效的星期几

构建器模式与参数对象输入

Cherrio JS返回父div的所有图像SRC

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

在单击按钮时生成多个表单时的处理状态

如何压缩图像并将其编码为文本?

固定动态、self 调整的优先级队列

如何在加载页面时使锚定标记成为焦点

ReactJS在类组件中更新上下文

鼠标进入,每秒将图像大小减小5%

无法在vue3中的img src上使用v-BIND

使用JavaScript生成介于最小和最大(包括最小和最大)之间的随机数

使用new关键字或createElement()创建的自定义元素没有is:属性,为什么?