首页 > 解决方案 > 如何将 patchValues() 与在 (keyup.enter) 事件绑定上

问题描述

我正在尝试根据邮政编码字段填充城市。我可以使用带有 (keyup) 事件绑定的普通 html 标记来执行上述操作,但是对于 css,我必须使用 (keyup.enter) 它能够调用与事件调用绑定的函数,但它不允许patchValue() 函数正常工作。这是我的代码片段:-

编辑器.component.ts

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


func(event: any){
  this.profileForm.patchValue({
      address:{
      city: this.getCity(event.value)
      }
    })  
}

getCity = (theCurrentZip: any) => {
  return Object.keys(this. zipCode).filter(z => {
    return this.zipCode[z].includes(theCurrentZip)
  })[0]
}

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

editor.component.html

<div>
<form (ngSubmit)="onSubmit()" #myForm="ngForm" class="profileForm">
<mat-form-field required>
  <input matInput id="name" placeholder="Contact Name" name="name" [(ngModel)]="name">
</mat-form-field >
<div formGroupName="address">
<mat-form-field >
    <input matInput id="zip" (keyup)="func($event.target)" placeholder="Zip" name="zip" [(ngModel)]="zip" >
  </mat-form-field >
  <mat-form-field required>
    <input matInput id="city" placeholder="City" name="city" [(ngModel)]="city" >
  </mat-form-field >
</div>
<p>
    <button type="submit" mat-raised-button color = "primary">Submit</button>
</p>
</form>
</div>

标签: javascriptangulartypescript

解决方案


据我所知,您目前正在混合 Angular 表单的反应式模板驱动的方法。

反应式方法用于您的editor.component.ts和模板驱动的方法editor.component.html

由于您的 HTML 是模板驱动的,因此无需调用patchValue,因为表单和表单控件未绑定到 HTML。因此,要更新您的 HTML,您需要调整您的实现,func如下所示

func(event) {
  this.city = this.getCity(event.target.value);
}

我对您的建议是您选择其中一种方法并且不要混合使用它们(如果不是绝对必要的话)。此外,您应该使用比func;)更有意义的函数名称


推荐阅读