Reputation: 1848
I've been doing some research on this and still can't find a good solution. Basically I have this basic form, that if I click on Clear button I want to rest form. Currently it resets it , but you will see that it shows the error message of the field for a half of a second then disappears. My question is: How to reset the form so it clears all the values from each field and never show any error message. Thanks a lot in advance!
Here's my code:
clearForm(){
this.registrationFormGroup.reset();
}
Upvotes: 1
Views: 406
Reputation: 602
You could change your logic to check for specific error like this:
userlastname.touched && userlastname.hasError['minLength']
.
As for using valid/invalid - I think there is a time where you have blurred out the field and show error message when you click on button.
EDIT
The above answer was wrong. The only way I was able to get it working is do a double reset. You need to call clearForm
on both mousedown
and click
.
If you only call clearForm
on mousedown
it will set the form to touched on click
(mouseup), on the other hand, if you only call clearForm
on click
, the erorr message would have been appeared when mousedown
. Live demo fork from yours.
Upvotes: 1
Reputation: 1950
Can you try this to modify your form like this :
<form [formGroup]="registrationFormGroup" #registrationFormDirective="ngForm" (ngSubmit)="onSubmit()" >
and the clearForm
function like this :
clearForm(registrationFormGroup: FormGroup, registrationFormDirective: FormGroupDirective){
registrationFormDirective.resetForm();
registrationFormGroup.reset();
}
Because the form status is in the FormGroupDirective and not in the FormGroup.
Upvotes: 0