2017-07-25 54 views
0

我觉得这应该很简单,但我找不到任何东西(至少没有大量的开销编码),我的特殊用例。基本上我有一个不是模式的更新配置文件页面。一旦用户更新,我希望表单重新恢复到原始状态并使用当前值,以防用户想要进行更多编辑。更新后的角度4重置表单 - 保持ngModel值(使用ngForm)

我使用ngForm的reset()(也试过resetForm())。这将它重置为原始等,但它也会删除输入中的所有值。在我使用的每个输入上使用[(ngModel)]="userRecord.phone"等。我的userRecord仍然正确。

是否有简单的方法来保留或取回重置后的模型值?

onSubmit(event, profileForm: NgForm) { 
    event.preventDefault(); 

    const myTempVar = this.userRecord; 
    this.userRecord.put() 
    .catch((e) => { 
     this.isProcessing = false; 
     return Observable.of(false); 
    }) 
    .subscribe((response) => { 
     this.displayConfirmation = 'Profile has been updated successfully.' 
     this.isProcessing = false; 
     this.userRecord = myTempVar; 
    }, (err) => { 
     console.log('There was an error saving', err); 
     this.displayError = 'Unknown error. Please refresh this page and try again.' 
     this.isProcessing = false; 
    }); 
} 

如果它有助于可视化,这里是提交之前的原始画面: original

这被提交后,如果我做一个ngForm reset()with reset

这如果我不做重置。我希望它是这样的,除了还质朴,并得到提交按钮再次启用(虽然现在我注意到,如果我做了复位是没有发生,反正:-()。 without reset

+0

当用户提交from时,是否将新值应用于'userRecord'变量? –

+0

是的,完全是约翰 - 不希望数据发生变化。 –

+0

Praveen,提交后我不会将任何新值应用于userRecord,但我可以从数据库刷新我想。 –

回答

1

之前你提交表单,你可以克隆你的表单数据到一些TMP对象:

tmpFormData: someType = Object.assign({}, currentData); 

然后你做reset()后,你可以做​​

+0

谢谢!我没有ngForm'patchValue()',但'setValue()'做了窍门! –

0

执行此提交成功后

这应该重新分配模型的价值。

+0

不幸的是,这并没有工作,我不知道在这一点上,它知道刷新ngModel值?(实际上不知道为什么没有工作,似乎应该有! –

+0

你可以分享你的代码? –

+0

当然,增加了问题 –