单击保存按钮时的 FormArray 不显示垫错误
FormArray on save button click does not display mat error
我在表单外有一个保存按钮。在保存按钮上单击我要显示 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
}
}
将整个 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
做了更多修改,以便它们仅在 FormField
为 touched
且无效时显示。此外,理想的用户体验应该是 disable
首先点击保存按钮。并在用户触摸字段时向用户显示错误。此外,将字段标签标记为必填项(*
) 可以被视为良好的用户体验。
我在表单外有一个保存按钮。在保存按钮上单击我要显示 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
}
}
将整个 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
做了更多修改,以便它们仅在 FormField
为 touched
且无效时显示。此外,理想的用户体验应该是 disable
首先点击保存按钮。并在用户触摸字段时向用户显示错误。此外,将字段标签标记为必填项(*
) 可以被视为良好的用户体验。