[英]Angular Reactive form submits twice and shows invalid error message after successful submission
我有一个带有自定义 ErrorStateValidation 的 Angular 反应式表单。 期望的行为是这样的:
我有 #1 使用自定义 ErrorStateMatcher。 成功提交后,我在 FormGroupDirective 上调用 resetForm function,它确实将提交状态重置为 FALSE。 问题是,表单似乎被提交了两次,因此提交状态自动返回 TRUE,并在成功提交后立即显示无效消息。
这个问题的工作示例可以在这里找到https://stackblitz.com/edit/add-angular-material-p9btep?devtoolsheight=33&file=src/app/app.component.ts
这是因为表单提交事件的冒泡。 您的表单被提交了两次:
onKeyUp
我建议您使用 click/enter 删除手动提交,并将(ngSubmit)
添加到您的表单中,并使用浏览器行为对您有利,如下所示:
<h1>Angular Forms Example</h1>
<form
[formGroup]="empForm"
#empFormDirective="ngForm"
(ngSubmit)="onAddEmpTopic($event, empFormDirective)" <!-- add this -->
>
<mat-form-field appearance="standard">
<mat-label>Add a topic</mat-label>
<input
matInput
[errorStateMatcher]="customErrorStateMatcher"
placeholder="I wish to discuss..."
formControlName="empTopic"
/>
<mat-error *ngIf="empTopic.errors?.required"
>Topic must not be empty.</mat-error
>
</mat-form-field>
<button mat-button>
<mat-icon>note_add</mat-icon>
</button>
</form>
需要延迟工作。
问题是提交事件与重置事件发生冲突,通常表单将通过 api 异步调用提交,您将在可观察和 promise 响应内的 200 响应上重置表单。
console.log(' Call API to add a topic!');
// set timeout can represent subscription or promise response.
setTimeout(() => {
empFormDirective.resetForm(empFormDirective.value);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.