reactive forms - on Submit, check if there is at least one change in the form and only then call the API

我们两清 提交于 2019-12-11 12:13:32

问题


What I want to achieve is something like this:

  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?


回答1:


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!");
    }
  }

Here is forked Stackblitz



来源:https://stackoverflow.com/questions/54673450/reactive-forms-on-submit-check-if-there-is-at-least-one-change-in-the-form-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!