[英]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我试图添加一个提交的变量和 this.myForm.markAsUntouched() 但剂量不起作用
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我能够通过将 #formDirective="ngForm" 放在表单标签中来解决这个问题
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" #formDirective="ngForm">
And declare并声明
@ViewChild('formDirective') private formDirective: NgForm;
You can then put .resetForm()然后你可以把 .resetForm()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.