Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Resetting form ignores initial value

Tags:

forms

angular

I have an Angular 2 app where I set default values for certain inputs like this:

this._stdSearchForm = this._formBuilder.group({
    count: [{value: 50, disabled: false}, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern("^[0-9]+$")])]
});

I have inplemented a "reset" feature like this:

(click)="resetStdSearchForm()"

and that just runs:

this._stdSearchForm.reset();

That resets the form, but ignores the initial value defined in the FormBuilder group.

Is this behaviour intended?

Can I programatically set the value of "count" after resetting the form? I tried doing this:

this._stdSearchForm.value.count = 50;

but that changed nothing.

like image 802
Glenn Utter Avatar asked Sep 20 '16 09:09

Glenn Utter


People also ask

What does reset form do in angular?

In a model-driven form to reset the form we just need to call the function reset() on our myform model. The form now resets, all the input fields go back to their initial state and any valid , touched or dirty properties are also reset to their starting values.

How do you clear a reactive form?

In Reactive forms, we need to import FormGroup from '@angular/forms' . After importing the above-mentioned modules in the respective approach, angular forms module provides an inbuilt method called reset(). We can use the method and we can reset the form.

How do I reset a template driven in angular 10?

To reset template-driven form, NgForm provides resetForm() method that is called as following. To call the above function, create a button in UI. If we want to reset form with some default values, then assign the default values with form control name of the form.


1 Answers

You can try the following:

this._stdSearchForm.setValue({ count: 50});

or you can do the same by:

this._stdSearchForm.reset({ count: 50});

The reset method resets the FormGroup. This means by default:

  • The group and all descendants are marked pristine
  • The group and all descendants are marked untouched
  • The value of all descendants will be null or null maps
like image 183
yurzui Avatar answered Oct 02 '22 03:10

yurzui