Reputation: 69
My expected results is to reset the form after it has been submit and set its default values binded to the formGroup control. I am attempt to reset the form to its default data after submitting by calling reset() on the form submit. Please advise me on how can I reset the default value in the date and time field .
Example :
pickupDate = new Date().toISOString().slice(0,10);
pickupTime = moment().format() ;
onSubmit(orderData: Order){
this.apiService(orderData).subscribe( order => {
orderForm.reset()
})
}
Please help Thanks
Upvotes: 5
Views: 32775
Reputation: 187
What I have found convenient is to segregate the form creation into a separate function. This way you can always reset the whole form just by calling the function.
public form: FormGroup;
private createForm(): void {
this.form = this.builder.group({
title: [ '', [Validators.required] ],
description: [ '', [Validators.required, Validators.maxLength(200)] ],
category: [ '', [Validators.required] ]
});
}
private onSubmit(data) {
this.apiService(data).subscribe(order => {
this.createForm();
});
}
Upvotes: 0
Reputation: 93
You can reset and set the default values you want at the same time like this:
defaultFormValues: any = {
date: Date.now
};
formG: FormGroup = new FormGroup({
'date': new FormControl(this.defaultFormValues.date)
});
onSubmit(orderData: Order) {
this.apiService(orderData).subscribe(order => {
this.formG.reset(this.defaultFormValues);
});
}
Upvotes: 3
Reputation: 6983
After submitting your form. you are calling
this.yourForm.reset()
Then you can patch initial values to the form like this.
this.yourForm.patchValue({
firstControllerName: this.initialValues.value1,
secondControllerName: this.initialValues.value2,
// other controller names goes here
});
Hope this helps.
Upvotes: 12
Reputation: 1263
I don't know how your formBuilder looks like, but
this.yourForm.reset({}) already does the trick to empty fields that weren't predetermined. You could attempt something similar to this...
ngOnChanges() {
this.queryForm.reset({
});
// We generate an empty form again.
this.createForm();
}
And your createForm could look like this...
createForm() {
// As the method name suggests, we create a form. A form consists of Groups, Controls - and optionally - Arrays...
this.queryForm = new FormGroup({
query: new FormControl(''),
formArray: new FormArray([this.initQueryConditions())
})
}
Upvotes: 4
Reputation: 2078
Approach for clearing depends whether you are using Template driven forms or Reactive forms.
Angular Forms, check full syntax with explaination
If template, then you need to set the model object to a default one (not necessarily empty). If reactive, then call a method which explictly empties each of form's value.
After that, do the form.Reset to move it back to "pristine | unchanged" state, thus removing validators as well
Upvotes: 0