Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ''.

like image 821
davecar21 Avatar asked Mar 04 '23 13:03

davecar21


1 Answers

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();
}
like image 58
Pardeep Jain Avatar answered Mar 07 '23 03:03

Pardeep Jain