问题
What I want to achieve is something like this:
- 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.
- If there are not any changes, just show a warning message to the user - "Hey you need to update something!"(console.log() is enough)
- *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