响应式表单 - 在提交时,检查表单中是否至少有一处更改,然后才调用 API [英] reactive forms - on Submit, check if there is at least one change in the form and only then call the API

查看:17
本文介绍了响应式表单 - 在提交时,检查表单中是否至少有一处更改,然后才调用 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的是这样的:

What I want to achieve is something like this:

  1. 当用户点击提交按钮时,在后台我需要比较表单的状态是否发生了变化,状态我的意思是至少有对表单进行一次更改,然后调用 API/服务器来保存信息.
  2. 如果没有任何更改,只需向用户显示警告消息 - 嘿,您需要更新某些内容!"(console.log() 就足够了)
  3. *当用户在 field1 中更改某些内容时,我还需要处理这种情况,例如,从胡萝卜变为美味的胡萝卜,然后又变回胡萝卜(不要调用 API).
  1. When the user clicks on Submit button, in the background I need to compare if the state of the form has changed, by state I mean if there is at least one change in the form and only then call the API/Server to save information.
  2. If there are not any changes, just show a warning message to the user - "Hey you need to update something!"(console.log() is enough)
  3. *I also need to handle this case when the user changes something in the field1, for example, from carrot to tasty carrot and then again back to a carrot(don't call API).

目前我有这样的东西 - 代码示例

At the moment I have something like this - code example

是否可以使用 pristine/dirty/touched/untouched 属性来做到这一点?

Is it possible to do that using pristine/dirty/touched/untouched properties?

推荐答案

可以使用脏检查,RxFormBuilder 提供了一个方法 isDirty() 来检查您的 formControl 值是否进行了任何更新.您只需要从 @rxweb/reactive-form-validators 包中导入 FormGroupExtension 和 RxFormBuilder ,您必须通过 RxFormBuilder 创建一个表单组.由于您想检查 onSubmit 单击是否有任何更新,您可以尝试在提交按钮单击

It is possible using dirty check, RxFormBuilder provides a method isDirty() to check whether any updates are made in your formControl values.You just need to import FormGroupExtension and RxFormBuilder from @rxweb/reactive-form-validators package, you have to create a formgroup through RxFormBuilder . As you want to check onSubmit click whether any update is made of not, you can try using this method on your submit button click

 onSubmit() {
    let isDirty = (<FormGroupExtension>this.myForm1).isDirty();
    if(isDirty)
    {
       this.http.post(this.api, this.myForm1);
    }
    else{
      console.log("Hey you need to update something!");
    }
  }

这里是分叉的Stackblitz

这篇关于响应式表单 - 在提交时,检查表单中是否至少有一处更改,然后才调用 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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