angular - 显示角度反应形式的错误消息的最佳方法,一个表单控制多个验证错误?
问题描述
我根据 angular angular form validation error example的建议方法显示反应式错误消息。
在页面上显示错误的html代码:
<div [formGroup]="myForm">
<div>
<input type="text" formControlName="firstName"/>
<div *ngIf="myForm.controls.firstName.invalid"
class="alert alert-danger">
<div *ngIf="myForm.controls.firstName.errors.required">
This Field is Required.
</div>
<div *ngIf="myForm.controls.firstName.errors.maxlength">
your can enter only 50 characters
</div>
</div>
</div>
<div>
<input type="text" formControlName="lastName"/>
<div *ngIf="myForm.controls.lastName.invalid"
class="alert alert-danger">
<div *ngIf="myForm.controls.lastName.errors.required">
This Field is Required.
</div>
<div *ngIf="myForm.controls.lastName.errors.maxlength">
your can enter only 50 characters
</div>
</div>
</div>
</div>
仅供参考我的组件代码如下:
this.myForm = this.formBuilder.group({
firstName:['',[Validators.required,Validators.maxLength(50)]],
lastName:['',[Validators.required,Validators.maxLength(50)]]
})
如果您看到上面的代码,我已经对我的名字和姓氏字段应用了两个验证。
为了显示错误消息,我编写了多个 *ngIf 条件来显示错误消息。
有没有最好的方法来显示特定控件的验证消息而无需编写多个 *ngIf 条件?因为我一次又一次地使用不同的控件名称和验证器名称编写相同的代码来显示错误消息。
解决方案
我建议有一个print-error
可以处理任何类型的 OOTB 或自定义错误的组件。
您可以处理任意数量的错误。
打印错误.component.ts
import {Component, Input} from '@angular/core';
@Component({
selector: 'print-error',
templateUrl: './print-error.component.html',
providers: []
})
export class PrintError {
@Input("control")
control: any;
}
打印错误.component.html
<div class="text-danger" *ngIf="control && control.errors && (control.dirty || control.touched)">
<div *ngIf="control.errors.required"><small>This field is required</small></div>
<div *ngIf="control.errors.unique"><small>{{control.errors.unique}}</small></div>
<div *ngIf="control.errors.lessThen"><small>{{control.errors.lessThen}}</small></div>
<div *ngIf="control.errors.greaterThan"><small>{{control.errors.greaterThan}}</small></div>
<div *ngIf="control.errors.email"><small>{{control.errors.email}}</small></div>
<div *ngIf="control.errors.mobile"><small>{{control.errors.mobile}}</small></div>
<div *ngIf="control.errors.confirmPassword"><small>{{control.errors.confirmPassword}}</small></div>
</div>
用法
<label for="folder-name">Email</label>
<input name="email" required emailValidator #email="ngModel" [(ngModel)]="user.email">
<print-error [control]="email"></print-error>
推荐阅读
- excel - 如何在保留公式的同时将小数显示为百分比
- r - SD 组内 MLA 使用 statsby
- javascript - 组织数据以从 .json 文件制作表格
- dataframe - 在 weka 上插入 - 不向我显示文件
- c# - 如何在带有 Dapper 的 Windows 窗体应用程序中直接从 PictureBox 保存图像,而无需使用 Dapper 存储过程?
- amazon-s3 - AWS SDK 3 WriteGetObjectResponseCommand 问题
- php - Wordpress 后分页不起作用重定向回发
- react-native - react-native 使用 FCM 推送通知 IOS & Android
- python - 在项目中使用两个连接器时如何正确关闭 MariaDB 和 MySQL 连接
- angular - RxJs:类型“未知 []”不可分配给类型“课程 []”