【问题标题】:Angular material reset form after submit提交后角材料重置表格
【发布时间】:2020-07-09 11:27:45
【问题描述】:

我使用有角度的材料,并且我有一个带有反应验证的表单。

我想在提交后重置我的表单,我的问题是提交后我看到我的错误出现在表单中。

输入示例:

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

我试图添加一个提交的变量和 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();
}

使用提交的变量,我看到消息错误消失了(下面的黄色部分),但没有看到边框和红色。

你们有什么想法可以解决这个问题吗?

【问题讨论】:

    标签: javascript validation angular-material submit


    【解决方案1】:

    我可以通过在表单标签中添加#formDirective="ngForm" 来解决这个问题

    <form [formGroup]="myForm" (ngSubmit)="onSubmit()" #formDirective="ngForm">
    
    

    并声明

    @ViewChild('formDirective') private formDirective: NgForm;
    
    

    然后你可以把 .resetForm()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 2019-04-04
      • 2018-04-13
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 2019-10-30
      相关资源
      最近更新 更多