I have a form on my page and when I call FormGroup.reset()
it sets the forms class to ng-pristine ng-untouched
but FormControl.hasError(...)
still returns truthy. What am I doing wrong here?
Template
<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)"> <mat-form-field> <input matInput formControlName="email" /> <mat-error *ngIf="email.hasError('required')"> Email is a required feild </mat-error> </mat-form-field> <mat-form-field> <input matInput type="password" formControlName="password" /> <mat-error *ngIf="password.hasError('required')"> Password is a required feild </mat-error> </mat-form-field> <button type="submit">Login</button> </form>
Component
export class MyComponent { private myForm: FormGroup; private email: FormControl = new FormContorl('', Validators.required); private password: FormControl = new FormControl('', Validators.required); constructor( private formBuilder: FormBuilder ) { this.myForm = formBuilder.group({ email: this.email, password: this.password }); } private submitForm(formData: any): void { this.myForm.reset(); } }
Plunker
https://embed.plnkr.co/Hlivn4/
Either first use “clearValidators()” to remove all validators and then use “setValidators()” to set needed validation.
reset()linkResets the form control, marking it pristine and untouched , and resetting the value.
FormBuilder allows us to explicitly declare forms in our components. This allows us to also explicitly list each form control's validators.
It (FormGroup
) behaves correctly. Your form requires username and password, thus when you reset the form it should be invalid (i.e. form with no username/password is not valid).
If I understand correctly, your issue here is why the red errors are not there at the first time you load the page (where the form is ALSO invalid) but pop up when you click the button. This issue is particularly prominent when you're using Material.
AFAIK, <mat-error>
check the validity of FormGroupDirective
, not FormGroup
, and resetting FormGroup
does not reset FormGroupDirective
. It's a bit inconvenient, but to clear <mat-error>
you would need to reset FormGroupDirective
as well.
To do that, in your template, define a variable as such:
<form [formGroup]="myForm" #formDirective="ngForm" (ngSubmit)="submitForm(myForm, formDirective)">
And in your component class, call formDirective.resetForm()
:
private submitForm(formData: any, formDirective: FormGroupDirective): void { formDirective.resetForm(); this.myForm.reset(); }
GitHub issue: https://github.com/angular/material2/issues/4190
After reading the comments this is the correct approach
// you can put this method in a module and reuse it as needed resetForm(form: FormGroup) { form.reset(); Object.keys(form.controls).forEach(key => { form.get(key).setErrors(null) ; }); }
There was no need to call form.clearValidators()
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