reactive forms - on Submit, check if there is at l

2019-07-31 16:56发布

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条回答
地球回转人心会变
2楼-- · 2019-07-31 17:11

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

查看更多
登录 后发表回答