简体   繁体   中英

Angular material reset form after submit

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 ?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM