首页 文章

单击保存按钮上的FormArray不显示mat错误

提问于
浏览
0

我在表格外面有一个保存按钮 . 在保存按钮单击我想显示 mat error . 但它没有显示出来 . 我尝试使用 this.form.markAsDirty()this.form.markASTouched() 但没有任何作用 .

<form [formGroup]="form">
 <div formArrayName="products" *ngFor="let product of form.get('products').controls; let i = index;">
  <div [formGroupName]="i">
    <mat-form-field>
      <input type="text" formControlName="productCode">
      <mat-error>
          Blank Error
      </mat-error>
    </mat-form-field>
    <mat-form-field>
      <input type="text" formControlName="productName">
      <mat-error>
          Blank Error
      </mat-error>
    </mat-form-field>
   </div>
  </div>
<form>
<div>
   <button type="button" (click)="SaveProducts()">Save</button>
</div>

angular code:

addProduct() {
  this.form.get('products').push(this.getProductGroup())
}

SaveProducts() {
  this.form.markAsDirty();
  this.form.markAsTouched();
  if(this.form.valid) {
     //save products
  }
}

1 回答

  • 0

    将整个 FormGroup 标记为 touched 并不会使它成为一个你必须明确做的事情,因为Angular不会隐含地这样做 . 阅读this thread以获取有关其背后的基本原理的更多信息 .

    话虽这么说,你可以在 'products' FormArray 中的每个 FormGroup 中的每个 FormControl 上显式调用 markAsTouched .

    这是如何做:

    (<FormArray>this.form.get('products')).controls.forEach((group: FormGroup) => {
      (<any>Object).values(group.controls).forEach((control: FormControl) => { 
          control.markAsTouched();
      }) 
    });
    

    这是你的参考号Working Sample StackBlitz .


    PS:我对 mat-error 进行了一些修改,以便它们仅在 FormFieldtouched 且无效时出现 . 此外,理想的用户体验是首先使用“保存”按钮 . 并在用户触摸字段时向用户显示错误 . 此外,根据需要标记字段标签( * )可以被视为一个良好的用户体验 .

相关问题