You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在<mat-form-field>的(keyup.enter)事件绑定中使用patchValue()

问题原因

  • 核心是你同时使用了Angular的响应式表单(FormBuilder/FormGroup)和模板驱动表单(ngModel)两套逻辑,二者的状态管理互相冲突,所以patchValue更新了表单模型的值,但没法同步到输入框视图上。
  • 切换到keyup.enter事件时,要注意输入值的获取方式不要出错,同时如果输入的邮编不在预设列表里,返回的undefined也可能导致赋值失效。

修复步骤

1. 修正HTML模板(editor.component.html)

移除所有ngModel绑定,补充响应式表单对应的绑定属性:

<div>
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" class="profileForm">
<mat-form-field required>
  <input matInput id="name" placeholder="联系人姓名" formControlName="name">
</mat-form-field >
<div formGroupName="address">
<mat-form-field >
    <input matInput id="zip" (keyup.enter)="func()" placeholder="邮编" formControlName="zip" >
  </mat-form-field >
  <mat-form-field required>
    <input matInput id="city" placeholder="城市" formControlName="city" >
  </mat-form-field >
</div>
<p>
    <button type="submit" mat-raised-button color = "primary">提交</button>
</p>
</form>
</div>

2. 修正TS逻辑(editor.component.ts)

调整func函数直接从响应式表单取当前邮编值,给getCity加兜底逻辑避免返回undefined:

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';

// 你原有组件装饰器代码保留
@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})
export class EditorComponent {
  constructor(private fb: FormBuilder) {}

  profileForm = this.fb.group({
      name: ['', Validators.required],
      address: this.fb.group({
               zip: ['', Validators.required],
               city: ['', Validators.required]
      })
  });

  func(){
    const currentZip = this.profileForm.get('address.zip')?.value;
    const city = this.getCity(currentZip);
    // 只有查到对应城市才赋值,避免清空原有值
    if(city) {
      this.profileForm.patchValue({
        address:{
          city: city
        }
      })
    }
  }

  getCity = (theCurrentZip: any) => {
    if(!theCurrentZip) return '';
    return Object.keys(this.zipCode).filter(z => {
      return this.zipCode[z].includes(theCurrentZip.trim())
    })[0] || '';
  }

  zipCode: any = {
    "A": ["1", "2" ],
    "B":[ "3", "4"]
  };

  // 你原有onSubmit方法保留
  onSubmit() {
    console.log(this.profileForm.value);
  }
}

验证效果

修改完成后在邮编输入框输入1、2、3、4任意值,按下回车即可自动填充对应的城市A/B,patchValue的更新会自动同步到输入框视图。

内容的提问来源于stack exchange,提问作者pratyaksh sudan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:57:03