Home:ALL Converter>Angular Reactive form submits twice and shows invalid error message after successful submission

Angular Reactive form submits twice and shows invalid error message after successful submission

Ask Time:2021-11-27T20:06:26         Author:Daniel McIntyre

Json Formatter

I have an Angular Reactive form with a custom ErrorStateValidation. The desired behavior is this:

  1. Only show invalid error message when a field has been submitted and there is nothing entered in the text input field.
  2. If the form has been successfully submitted, reset validation and submit status to false and do not show the invalid error message.

I have #1 working with the custom ErrorStateMatcher. After successful submission, I'm calling the resetForm function on the FormGroupDirective which DOES reset the submit status to FALSE. The problem is, the form seems to be getting submitted twice so the submit status goes back automatically to TRUE and immediately shows the invalid message after successful submission.

Working example of this problem can be found here https://stackblitz.com/edit/add-angular-material-p9btep?devtoolsheight=33&file=src/app/app.component.ts

Author:Daniel McIntyre,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70134622/angular-reactive-form-submits-twice-and-shows-invalid-error-message-after-succes
deepakchethan :

This is because of bubbling of form submit event. Your form is being submitted twice:\n\nManually by button click or onKeyUp with enter key\nSubmission by the browser automatically since you used form\n\nI suggest you remove the manual submission with click/enter and add the (ngSubmit) to your form and use browsers behaviour to your advantage instead as follows:\n<h1>Angular Forms Example</h1>\n\n<form\n [formGroup]="empForm"\n #empFormDirective="ngForm"\n (ngSubmit)="onAddEmpTopic($event, empFormDirective)" <!-- add this -->\n>\n <mat-form-field appearance="standard">\n <mat-label>Add a topic</mat-label>\n <input\n matInput\n [errorStateMatcher]="customErrorStateMatcher"\n placeholder="I wish to discuss..."\n formControlName="empTopic"\n />\n <mat-error *ngIf="empTopic.errors?.required"\n >Topic must not be empty.</mat-error\n >\n </mat-form-field>\n <button mat-button>\n <mat-icon>note_add</mat-icon>\n </button>\n</form>\n\nWorking example: https://stackblitz.com/edit/add-angular-material-j1wjno?devtoolsheight=33&file=src%2Fapp%2Fapp.component.html",
2021-11-27T13:12:41
yy