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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With