angularangular-forms

Angular Form reset value and set all its initial value rather than null


For example I have a form below.

searchForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl('')
  })

The problem is that when I use searchForm.reset() the initial value is set to null and not to empty string '' that I set as an initial value in the FormControl.

I have tried doing the code below and it works. The problem is that for example I have like 20 FormControl, I will need to type it all and initialize it in .reset({firstName:'', other20properties..})

this.searchForm.reset(
      {
        firstName: '',
        lastName: ''
      }
    );

Is there a way to reset the form and set all its initial value to empty string ''.


Solution

  • In these type of scenarios better to wrap your form initialization into a separate method and call that method after form.reset like this -

    formInit() {
     searchForm = new FormGroup({
        firstName: new FormControl(''),
        lastName: new FormControl('')
     })
    }
    
    
    anotherFunction() {
      this.searchForm.reset();
      this.formInit();
    }