本文介绍了将表单设置为“原始"而不清除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示<input type="text">元素列表的表单.它们都共享一个公共的保存按钮,该按钮在表单变脏之前将被禁用.然后,一旦用户单击保存按钮,数据将被提交到服务器.如果服务器成功保存了数据,我想将表单重置为原始状态,但是我想将所有数据保留在表单中,以便用户可以选择进一步编辑数据.

I have a form that displays a list of <input type="text"> elements. They all share a common save button which is disabled until the form becomes dirty. Then, once the user clicks the save button, the data will be submitted to the server. If the server successfully saved the data, I want to reset the form to a pristine state, but I want to keep all of the data in the form so the user can edit the data further if they so choose.

搜索后,我找到了NgForm.reset()方法.尽管这确实使表格原始,但不幸的是,它也清除了表格. reset方法似乎确实具有值参数,但我似乎无法找出它的作用.但是,我不想清除数据.

After searching, I have found the NgForm.reset() method. While this does set the form to pristine, it unfortunately also clears out the form. The reset method does seem to have a value parameter, but I can't seem to find out what it does. Nevertheless, I don't want the data cleared out.

我也尝试过myForm.pristine = true,但是由于某种原因,这会导致页面重新加载.

I have also tried myForm.pristine = true as well, but this causes a reload of the page for some reason.

这是一个展示问题的小问题.

推荐答案

目前,我可以提出两种可能的解决方案.第一个与您的建议非常接近,因为form的reset方法具有以下签名,并且接受form值作为第一个参数:

At the moment I can suggest two possible solutions.First one is really close to what you've suggested, as form's reset method has following signature and accepts form value as a first argument:

//@angular/forms/src/model.d.ts:
reset(value?: any, {onlySelf}?: { onlySelf?: boolean; }): void;

在提交处理程序中,我们将捕获最后一个状态的副本:

In the submit handler, we will capture a copy of the last state:

const { myForm: { value: formValueSnap } } = this;

然后自行重置:

this.myForm.reset(formValueSnap, false);

当无法重新设置表单时,另一个选择是创建一个辅助方法,该方法将每个控件标记为pristine并保留数据.可以在同一提交助手中调用它来代替重置.

Another option from the times, when there was no possibility to reset form, is to create a helper method, which will mark each control as pristine and will keep the data. It can be called in the same submit helper in place of the resetting.

private _markFormPristine(form: FormGroup | NgForm): void {
    Object.keys(form.controls).forEach(control => {
        form.controls[control].markAsPristine();
    });
}

链接到更新的 plunkr .

这篇关于将表单设置为“原始"而不清除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:23
查看更多