javascript - 错误 TS2345 : Argument of type 'Event' is not assignable to parameter of type '{ target: { value: string; }; }'

标签 javascript angular events angular-event-emitter

我在构建 Angular 应用程序时遇到错误。

HTML 模板

  <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 - 错误 TS2345 : Argument of type 'Event' is not assignable to parameter of type '{ target: { value: string; }; }' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73329921/

相关文章:

javascript - Helenus 无法连接

javascript - 如何通过在JavaScript中构造AudioBuffer来正确播放WAV文件?

javascript - DevExpress 仪表板控件 - 在条形图轴标签上显示文本

javascript - 返回语句在 Ajax 和 Angular 中不起作用

angular - @ngrx 中效果中的链式操作

android - 钛 : android options all button events trigger at once

javascript - 如何打开包含用 javascript 编写的图形的弹出窗口?

django - Angular MSAL 库请求的 Azure AD 用户访问 token 以及使用 django_auth_adfs 通过 WEB API 进行的验证

c# - 防止C#中的重复代码

Delphi:单击控件时如何调用方法?