Reputation: 115
I use angular material and I have a form with reactive validation.
I want to reset my form after submitting, my issue is after submitting I see my errors appears in the form.
input example :
<mat-form-field>
<mat-label>Prénom</mat-label>
<input matInput name="prenom" formControlName="prenom">
<mat-error *ngIf="f.prenom.hasError('required') && submitted">
Ce champ est obligatoire
</mat-error>
<mat-error *ngIf="f.prenom.errors?.maxlength && !f.prenom.hasError('required')">
le prénom ne peut pas dépasser 20 caractères
</mat-error>
</mat-form-field>
I tried to add a submitted variable and this.myForm.markAsUntouched() but dosesn't work
onSubmit() {
this.submitted = true;
if (this.myForm.invalid) {
return;
}
alert('Form Submitted succesfully!!!\n Check the values in browser console.');
console.table(this.myForm.value);
this.submitted = false;
this.myForm.reset();
this.myForm.markAsUntouched();
}
With the submitted variable I see the message error disappear(the yellow section below) but not the border and red color.
Do you guys have any ideas to solve that ?
Upvotes: 2
Views: 3503
Reputation: 115
I was able to solve this by putting #formDirective="ngForm" in the form tag
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" #formDirective="ngForm">
And declare
@ViewChild('formDirective') private formDirective: NgForm;
You can then put .resetForm()
Upvotes: 5