javascript - 如何将 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>
解决方案
据我所知,您目前正在混合 Angular 表单的反应式和模板驱动的方法。
反应式方法用于您的editor.component.ts
和模板驱动的方法editor.component.html
。
由于您的 HTML 是模板驱动的,因此无需调用patchValue
,因为表单和表单控件未绑定到 HTML。因此,要更新您的 HTML,您需要调整您的实现,func
如下所示
func(event) {
this.city = this.getCity(event.target.value);
}
我对您的建议是您选择其中一种方法并且不要混合使用它们(如果不是绝对必要的话)。此外,您应该使用比func
;)更有意义的函数名称
推荐阅读
- python - 如何实现“软件中断”?
- git - git status 的 Git 别名列出了相对于存储库根目录的文件
- php - 如何将字符串添加到php函数内的数组中
- ruby-on-rails - Rails Action Mailer 在本地工作,但不能在生产环境中工作:Heroku:内部服务器错误
- python - 绘制熊猫 DataframeGroupbySeries 的 HIST
- javascript - 电子没办法换驱动?
- spring - 如果注解包含参数,建议不会执行
- google-chrome - Firefox Native addon(win7):如何在给定 Windows HWND 的情况下获取 window.id
- javascript - Chrome 扩展:如何在 2021 年安装类似 choex 的 ES6 npm 脚本?
- laravel - 如何在 Laravel 6 中隐藏 url 中的 id?