Angular Reactive 表单:如何在提交后重置表单状态并保留值 [英] Angular Reactive forms : how to reset form state and keep values after submit

查看:36
本文介绍了Angular Reactive 表单:如何在提交后重置表单状态并保留值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以 Angular 反应形式.成功提交后如何仅重置表单的状态?

In an Angular reactive form. How to reset only the state of form after successful submit?

流程如下:

  • 根据服务结果创建表单和setValue
  • 修改值并提交表单
  • 如果表单正确提交给服务,则重置并保留值

如何保持修改后的值并将表单重置为其原始状态.

form.reset() 只是清空表单.但是如果我不调用它,状态不会重置,例如我根据表单状态类(原始、脏、有效等)进行的验证仍然存在.

A form.reset() simply empty the form. But if I don't call it, the state is not reset and for example my validations depending on form state classes (pristine, dirty, valid etc.) are still there.

推荐答案

@smnbbrv 的解决方案效果很好.

The solution of @smnbbrv works pretty well.

您还可以将实际表单值提供给 reset() 方法.

You can also provide your actual form value to reset() method.

鉴于 myReactiveForm 是组件中的响应式表单.成功提交表单后(例如通过调用服务),您可以执行以下操作:

Given the fact myReactiveForm is a Reactive form in your component. After successful submit of your form (by calling a service for example), then your can do:

this.myReactiveForm.reset(this.myReactiveForm.value);

它将重置表单并将新"表单值设置为与表单相同的值.

It will reset the form and set the "new" form values to the same value you form had.

这个方法可以在 Tour of Hero 示例中看到 Angular.io 官方文档

This method can be see within Tour of Hero example Official Angular.io doc

这篇关于Angular Reactive 表单:如何在提交后重置表单状态并保留值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆