Angular 5中ngModel未保存却变更UI值的问题解决咨询
解决模态框中修改select值未保存却变更UI的问题
这个问题我之前也碰到过类似的坑,本质是你同时混用了响应式表单的formControlName和ngModel双向绑定导致的。ngModel会直接修改你绑定的newParameter.type对象——哪怕你没点保存就关闭模态框,这个对象的值已经被改掉了,所以UI会显示修改后的值,但数据库根本没更新。
具体解决步骤:
移除ngModel,只用响应式表单控制
Angular官方不推荐在响应式表单里混用ngModel,这会造成数据源混乱。直接去掉[(ngModel)]="newParameter.type",让表单控件单独管理值的变化。修改后的component.html:
<select class="form-control m-input" id="type" formControlName="type" [ngClass]="{ 'is-invalid': submitted && formcontrols.type.errors }" name="type" (change)="changeType($event)"> <option [ngValue]="'STRUCT'">STRUCT</option> <option [ngValue]="'NUM'">NUM</option> <option [ngValue]="'BOOLEAN'">BOOLEAN</option> <option [ngValue]="'DATE'">DATE</option> </select>打开模态框时保存原始值
在打开模态框的瞬间,把newParameter的初始值存下来,方便取消时恢复:// 假设这是打开模态框的方法 openModal() { // 保存type的原始值 this.originalType = this.newParameter.type; // 同步表单初始值 this.createParameterForm.patchValue({ type: this.newParameter.type }); // 其他模态框初始化逻辑... }关闭模态框时重置状态
如果用户选择不保存就关闭,需要同时重置表单和newParameter的状态:// 关闭模态框且不保存的方法 closeModalWithoutSave() { // 重置表单到初始状态 this.createParameterForm.reset({ type: this.originalType }); // 恢复newParameter的原始值 this.newParameter.type = this.originalType; // 执行关闭模态框的逻辑... }简化changeType方法
现在不需要传type参数了,直接从表单控件取值就行:changeType(event){ const type = this.createParameterForm.get('type').value; if(type==="NUM"){ this.initNUMControlsForm(); } else if(type ==="STRUCT"){ this.initStructControlsForm(); } else{ this.initControlsForm(); } }保存时再同步表单值到业务对象
只有当用户确认点击保存按钮时,才把表单的值同步到newParameter,再提交到数据库:saveParameter() { this.submitted = true; if(this.createParameterForm.valid) { // 同步表单值到newParameter this.newParameter.type = this.createParameterForm.get('type').value; // 执行保存到数据库的逻辑... // 保存成功后关闭模态框 this.closeModal(); } }
核心思路
响应式表单要遵循单一数据源原则,让表单控件管理所有值的变化,只有在确认保存时才把表单的值同步到业务对象(newParameter)。这样在用户取消操作时,我们可以轻松重置表单和业务对象的状态,彻底避免UI显示和数据库不一致的问题。
内容的提问来源于stack exchange,提问作者GigiProve
相关产品推荐
相关产品推荐

