我在表格外面有一个保存按钮 . 在保存按钮单击我想显示 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 回答
将整个
FormGroup
标记为touched
并不会使它成为一个你必须明确做的事情,因为Angular不会隐含地这样做 . 阅读this thread以获取有关其背后的基本原理的更多信息 .话虽这么说,你可以在
'products'
FormArray
中的每个FormGroup
中的每个FormControl
上显式调用markAsTouched
.这是如何做:
这是你的参考号Working Sample StackBlitz .
PS:我对
mat-error
进行了一些修改,以便它们仅在FormField
为touched
且无效时出现 . 此外,理想的用户体验是首先使用“保存”按钮 . 并在用户触摸字段时向用户显示错误 . 此外,根据需要标记字段标签(*
)可以被视为一个良好的用户体验 .