Angular 12模态框输入内容未点击提交就实时显示如何解决
Angular模态框输入实时同步问题修复方案
问题根因
你的代码同时混用了Angular响应式表单的formControlName和模板驱动表单的双向绑定[(ngModel)],且ngModel直接绑定到了页面渲染用的源对象userProfiles上,输入框的内容变化会直接修改该对象的属性,自然会同步到页面的展示位置,和是否提交没有关系。
修复步骤
- 移除HTML模板中输入框的
[(ngModel)]绑定,响应式表单不需要和ngModel混用,输入值会自动存储在updateForm实例的对应控件中,不会直接修改源对象:
<input type="text" class="form-control" formControlName="name" >
- 在模态框打开的触发逻辑中,把当前
userProfiles的最新值赋值给表单,作为初始默认值:
// 你触发打开模态框的方法中加入这段代码 this.updateForm.patchValue({ name: this.userProfiles.name, user_info: this.userProfiles.user_info })
- 修改提交方法
updateProfile,只有用户点击提交时,才把表单的最新值覆盖到源对象userProfiles上,再调用后端更新接口:
updateProfile(){ // 提交时才同步表单值到源对象 Object.assign(this.userProfiles, this.updateForm.value); this.dataService.updateProfile(this.userProfiles).subscribe(re=>{ $("#editProfile").modal("hide"); }) }
可选优化
你可以把按钮的点击事件替换为表单的ngSubmit事件,更符合Angular表单的使用规范:
<form class="comment-form" [formGroup]="updateForm" id="editProfileForm" (ngSubmit)="updateProfile()" > <input type="text" class="form-control" formControlName="name" > <button type="submit">Save</button> </form>
内容的提问来源于stack exchange,提问作者32quick23
相关产品推荐
相关产品推荐

