Set Form to Pristine without clearing data
What you're looking for is myForm.markAsPristine()
.
At the moment I can suggest two possible solutions.
First one is really close to what you've suggested, as form's reset
method has following signature and accepts form value as a first argument:
//@angular/forms/src/model.d.ts:
reset(value?: any, {onlySelf}?: { onlySelf?: boolean; }): void;
In the submit handler, we will capture a copy of the last state:
const { myForm: { value: formValueSnap } } = this;
And do the reset itself:
this.myForm.reset(formValueSnap, false);
Another option from the times, when there was no possibility to reset form, is to create a helper method, which will mark each control as pristine
and will keep the data. It can be called in the same submit helper in place of the resetting.
private _markFormPristine(form: FormGroup | NgForm): void {
Object.keys(form.controls).forEach(control => {
form.controls[control].markAsPristine();
});
}
Link to the updated plunkr.
If you happen to be using Template-Driven forms and you have something like this in your component:
@ViewChild('myForm') myform: NgForm;
I've found that the markAsPristine()
is a function on the form property of your form. So it would be this.myform.form.markAsPristine()
.
Just thought I'd add this in case others come across markAsPristine()
as not being defined.