When i first load the page, the form appears like this

But after i successfully create an announcement, i reset the page with this.announcementCreateForm.reset() code and it resets the below way

I call the below method buildAnnouncementForm() during ngOnInit()
private buildAnnouncementForm() {
this.announcementCreateForm = this.fb.group({
announcementTitle: ['', [Validators.required]],
announcementText: '',
announcementFor: ['', [Validators.required]],
announcementType: ['', [Validators.required]],
announcementFromDate: [this.announcementFromDate, Validators.required],
announcementToDate: [this.announcementToDate, Validators.required]
});
}
I call the reset method after success
resetAnnouncementPage() {
if (this.announcementCreateForm.valid) {
console.log("Reset...");
this.announcementCreateForm.reset();
this.announcementCreateForm.markAsPristine();
//this.announcementCreateForm.markAsUntouched();
}
}
My reset, wants me to bring the form like it looks during loading.. how to do it ?
If you want to revert the form in its initial state, then store that state in a value and use it to set the form value when you want to reset the form,
Don't do form.reset(), it will remove even the empty strings from the from controls.
initialFormValue = {
announcementTitle: '',
announcementText: '',
announcementFor: '',
announcementType: '',
announcementFromDate: this.announcementFromDate,
announcementToDate: this.announcementToDate
}
resetAnnouncementPage() {
if (this.announcementCreateForm.valid) {
console.log("Reset...");
this.announcementCreateForm.setValue(this.initialFormValue);
this.announcementCreateForm.markAsPristine();
}
}
Edit
You can also pass the value to reset with while doing a form reset().
private _initialValue
private buildAnnouncementForm() {
this.announcementCreateForm = this.fb.group({
announcementTitle: ['', [Validators.required]],
announcementText: '',
announcementFor: ['', [Validators.required]],
announcementType: ['', [Validators.required]],
announcementFromDate: [this.announcementFromDate, Validators.required],
announcementToDate: [this.announcementToDate, Validators.required]
});
this._initialValue = this.announcementCreateForm.value
}
resetAnnouncementPage() {
if (this.announcementCreateForm.valid) {
this.announcementCreateForm.reset(this._initialValue);
}
}
I followed these steps and achieved it
Added formDirective to the form and passed it to my onSubmit method
<form #formDirective="ngForm" (ngSubmit)="onSubmit(formDirective)" [formGroup]="announcementCreateForm">
passed the formDirective argument to my reset method and reset the formDirective first and then i did reset the form
resetAnnouncementPage(formDirective:FormGroupDirective) {
if (this.announcementCreateForm.valid) {
formDirective.resetForm();
this.announcementCreateForm.reset();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With