You need to enable JavaScript to run this app. Angular 8中使用(blur)的matInput文本框为何显示[object FocusEvent]而非实际文本?
优惠活动
大模型
产品
解决方案
定价
更多

Angular 8中使用(blur)的matInput文本框为何显示[object FocusEvent]而非实际文本?

Angular 8 项目matInput绑定blur事件后输入框显示[object FocusEvent]问题处理

异常现象

给matInput文本框绑定blur事件触发fetchContractNumber处理函数时,输入框无法正常展示用户实际录入的文本,反而直接显示[object FocusEvent]字符串。

问题根因

  • 模板中绑定blur事件时,直接将原生FocusEvent对象$event作为实参传入fetchContractNumber方法,和方法定义中预期的“合同编号字符串”形参不匹配
  • 方法内部第一行逻辑直接把收到的FocusEvent对象传给changeField方法,最终将该事件对象赋值回和输入框单向绑定的equipmentModel.previousContractNumber字段
  • 因为[ngModel]绑定的值被替换成了FocusEvent实例,浏览器在做非字符串类型的隐式转换时,会输出原生的[object FocusEvent]字符串,直接覆盖用户实际输入的内容

原始问题代码

组件业务逻辑代码

fetchContractNumber(contractNumber: any): void {
  this.changeField(contractNumber, 'vehicle.previousContractNumber');
  if (contractNumber) {
    this.s1 = this.facade.fetchContractNumber(this.equipmentModel.previousContractNumber).subscribe(data => {
      this.equipmentModel.previousWarrantyExpiryOdometer = data.data.contracts[0].expirationOdometer;
      this.equipmentModel.previousWarrantyExpiryDate = data.data.contracts[0].expirationDate;
      this.changeField(data.data.contracts[0].expirationOdometer, 'vehicle.previousWarrantyExpiryOdometer');
      this.changeField( data.data.contracts[0].expirationDate, 'vehicle.previousWarrantyExpiryDate');
    });
  }
}

模板绑定代码

<mat-form-field class="w-4/12 xl:w-4/12 pr-1">
  <input
    matInput
    (blur)="fetchContractNumber($event)"
    name="previousContractNumber"
    [ngModel]="equipmentModel.previousContractNumber"
    placeholder="{{ 'previouscontractnumber' | translate }}"
    type="text"
    #previousContractNumber="ngModel"
    [errorStateMatcher]="errorStateMatcher('vehicle.previousContractNumber', dealError)"
    [ngDave2EditableField]="dealIsLocked"
    editableFieldgroup="equipment"
    editableFieldCode="previousContractNumber"
    [editableDealStatus]="dealStatus"
  />
  <button
    mat-button
    *ngIf="equipmentModel.previousContractNumber && !dealIsLocked"
    matSuffix
    mat-icon-button
    aria-label="Clear"
    (click)="resetPreviousContractNumberFields()"
  >
    <mat-icon>close</mat-icon>
  </button>
  <mat-error>
    {{ 'required' | translate }}
  </mat-error>
</mat-form-field>

修复方案

只需要调整模板中的事件传参逻辑即可,无需改动核心业务逻辑,两种可选实现:

  • 复用现有模板引用变量取值:直接将blur事件的传参替换为指向ngModel实例的模板引用变量的value值,修改后的绑定代码为:(blur)="fetchContractNumber(previousContractNumber.value)"
  • 从原生事件对象中取值:如果需要依赖事件对象做额外处理,需要明确取事件目标的输入值,修改后的绑定代码为:(blur)="fetchContractNumber($event.target.value)"

注意:不要直接将原生DOM事件对象赋值给和表单绑定的字段,否则一定会触发隐式类型转换导致显示异常。


内容的提问来源于stack exchange,提问作者Karim Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 19:45:04