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

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

问题描述

我想要实现的是这样的:

What I want to achieve is something like this:

  1. 当用户单击提交"按钮时,在后台我需要比较表单的 state 是否已更改,按 state 的意思是至少存在只需更改一次表单,然后,然后调用API/服务器以保存信息.
  2. 如果没有任何更改,只需向用户显示一条警告消息-嘿,您需要更新!"(console.log()就足够了)
  3. *当用户在字段1中更改某些内容(例如,从胡萝卜更改为美味的胡萝卜,然后再次返回到胡萝卜(不调用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

是否可以使用原始/脏/触摸/未触摸属性来做到这一点?

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

推荐答案

可以使用脏检查,RxFormBuilder提供方法isDirty()来检查formControl值中是否进行了任何更新.您只需导入FormGroupExtension和@ rxweb/reactive-form-validators包中的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天全站免登陆