Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  41] [ 7]  / answers: 1 / hits: 79840  / 6 Years ago, fri, may 18, 2018, 12:00:00

I have some form and button to save it. The button must only be enabled when there are unsaved changes (inputs) on the form.



<form>
<div>
... (inputs)
<span (click)=save()> Save </span>
</div>
</form>


Is there some build-in mechanism for form dirty check in Angular 5? What is the easiest way to implement this scenario ?


More From » html

 Answers
11

Yes there is: I highly advise you to take a look at the documentation of reactive forms.



Apart from that, the built-in mechanism is only for checking the state of the form:




  • touched means the user has entered the form

  • dirty / !pristine means the user has made a modification



But if you want to handle changes made, you should not use that: if your username changes its username from foo, to bar, then back to foo, there is no changes in your form, so the user should not have to send the said form.



Instead, what I advise you is to make a function that compares the form to the original value of your object. Here is how you can do it:



// Creates a reference of your initial value
createReference(obj: any) {
this.reference = Object.assign({}, obj);
}

// Returns true if the user has changed the value in the form
isDifferent(obj: any, prop: string) {
return this.reference[prop] !== obj[prop];
}

submitForm(form: any) {
// ... Business code ...
hasChanges = false;
for (let prop in form) {
if (this.isDifferent(form, prop)) { hasChanges = true; }
}
// If no changes, cancel form submition
if (!hasChanges) { return; }
}

[#54412] Sunday, May 13, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
richardaydenc

Total Points: 148
Total Questions: 125
Total Answers: 98

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;