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

时间:2018-12-09 17:30:09

标签: angular angular-material2

我在表格外有一个保存按钮。在保存按钮上,单击我要显示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 :(得分:1)

将整个FormGroup标记为touched不会使它的子级受到感动。这是您必须显式执行的操作,因为Angular不会隐式地执行该操作。阅读this thread,了解有关其背后原理的更多信息。

话虽如此,您可以在markAsTouched FormControl中每个FormGroup的每个'products'上显式调用FormArray

方法如下:

(<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且无效时才显示它们。另外,理想的用户体验是首先使用disable“保存”按钮。并在用户触摸字段时向他们显示错误。同样,将字段标签标记为必填项(*)也可以被认为是不错的用户体验。