AJ-
AJ-

Reputation: 1783

Angular - Reactive form, how to correctly store the initial value, and check for changes in the form?

I'm using reactive forms with angular 6 and I have 2 questions.

First one, what's the correct way to store the initial value of a form?

I'm pretty new to angular, and what I've done so far, is to declare in the controller all the form code, and then in the view I bind those controls with the fromControlName tag.

Everything works correctly, but now I want to implement a Save/Cancel button. As the form comes prefilled based on some choices made by the user (I prefill the form with this.myForm.get("valueToPrefill").setValue(prefillValue)) so when the user opens the form, some fields will be already prefilled!

What I need to do, is, to clone somehow or store the initial data, so when the user is done editing, if he presses "Save", then this temporary form data will be written on the form (I guess with the same way I prefill it, get("form_Name).setValue() right?), but if he were to use the Cancel button, then I should revert to form to the original state!

Currently when an user fills a form value, it gets written directly on the form, because of the fromControlName tag, which binds the input fields to my form.

What should I do here to have a copy of the form to write on, and only after I save, it writes those value on the original form I declared in my controller?

Second question, currently my Save button gets disabled if the form is pristine. But I would want to go one step further! If a user deletes a characted, or changes a dropdown, but then reverts those changes by going back to the original value, the form is now dirty, but the data actually never changed from the initial status! So how can keep the Save button disabled in this case? I can imagine doing a check when I manage to have a cloned form, so I can check the initial data with the stored one, and compare them right?

Thank you very much

Upvotes: 0

Views: 4985

Answers (2)

Florian
Florian

Reputation: 1481

I edited your stackblitz
You don't need to have a copy of the form because you have your original data.
You need to identify your data, currently you only have grade and value which are two fields in the form. So I added an id to identify your pairs.

Upvotes: 1

MullisS
MullisS

Reputation: 278

you can simply use the @angular/forms API for that (https://angular.io/api/forms):

saveForm(){
this.savedFormState = formGroup.getRawValue()
}
resetForm(){
formGroup.patchValue(this.saveFormState);
// Reset states like dirty, markAsTouched
}

Note that the object has to match with your FormGroup.

Upvotes: 2

Related Questions