how to reset angular form and set default values after submitting

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

3 answers

  • answered 2018-04-17 05:05 NitinSingh

    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

  • answered 2018-04-17 05:05 ak.leimrey

    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())
        })
      }
    

  • answered 2018-04-17 05:05 Anuradha Gunasekara

    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.