angular - 如何处理默认的 Angular 表单验证错误?
问题描述
我在这里使用反应式表单验证。我有 3 个字段电子邮件、全名和密码(均为必填项)。当我只需单击任何一个字段并单击关闭字段时。默认情况下,Angular 在字段上显示红色边框
我想在输入字段并删除所有文本并单击外部时显示红色边框。
当我只是单击字段并单击字段时,我不想显示红色边框。
如何覆盖此默认行为?
模板
<form name="form" (ngSubmit)="onSubmit(signUpForm)" #f="ngForm"
#signUpForm="ngForm" [formGroup] = "signup"
fxShow="true" fxFlex fxLayout="column" fxLayoutAlign="center stretch" fxLayoutGap="4px">
<div>
<mat-form-field appearance="outline">
<mat-label>Email</mat-label>
<input matInput placeholder="Enter the email" name="email" formControlName="email">
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline">
<mat-label>Full Name</mat-label>
<input matInput placeholder="Enter your fullname" name="fullname" formControlName="fullname">
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline">
<mat-label>Password</mat-label>
<input matInput placeholder="Enter the password" name="password" formControlName="password">
</mat-form-field>
</div>
<div>
<button class="btn btn-info height_40" type="submit" [disabled]="signup.invalid" fxFlex="98">
Sign Up
</button>
</div>
</form>
打字稿文件
export class SignupComponent implements OnInit {
signup: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.signup = formBuilder.group({
email: ['', Validators.required],
fullname: ['', Validators.required],
password: ['', Validators.required]
})
}
}
解决方案
如文档中所述:
默认情况下,当控件无效并且用户与之交互(触摸)时会显示这些错误消息
您可以覆盖可以使用自定义errorStateMatcher的行为。通过扩展 ErrorStateMatcher 接口创建自定义 MyErrorStateMatcher。然后将此错误匹配器放在 matInput 元素上,如下所示:
组件.ts
/** Error when control is pristine. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
console.log(control!.touched && control!.dirty);
return !control!.pristine;
}
}
matcher = new MyErrorStateMatcher();
组件.html
<input type="email" matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
placeholder="Ex. pat@example.com">
推荐阅读
- internals - Reasonml 地图不纯?
- php - 使用codeigniter框架时如何在cpanel中安装composer?
- workbox - 如何使用 workbox.streams 修复服务工作者中的 fetch 事件
- mongodb - 如何在 mongoDB 中处理 $project 中的多个 $lookup 和大量列
- jquery - 如何使用 jquery 在下拉选择更改时显示/隐藏标签
- google-app-engine - 如何设置 GCP App Engine 服务的服务名称
- go - 谷歌云函数(Golang)和 Terraform
- amazon-web-services - 如何在 Cloudflare 中的另一个 ec2 实例 AWS 上添加子域?
- android - 如何在人脸识别应用程序中将相机方向从横向模式更改为纵向模式
- python - 如何使用 Requests 库生成带有参数的 POST 请求?