问题描述
我正在尝试使用 和
进行验证.当用户在没有填充的情况下退出输入时,这可以正常工作.但是如何在单击按钮时强制显示此错误?我没有使用提交.此外,使用模板驱动的表单.
这是我的代码:
HTML:
<input matInput placeholder =截止日期"名称=截止日期"[(ngModel)]=dueDate"[formControl]=dueDateValidator"需要><mat-error *ngIf=dueDateValidator.invalid">任务需要截止日期</mat-error></mat-form-field>
TS:
dueDateValidator: FormControl = new FormControl('', [Validators.required]);
查看如何使用带有自定义的表单 ErrorStateMatcher
如果您希望覆盖此行为(例如,尽快显示错误因为无效控件是脏的或父表单组是无效),您可以使用 matInput 的 errorStateMatcher 属性.该属性采用 ErrorStateMatcher 对象的实例.一个ErrorStateMatcher 必须实现一个方法 isErrorState获取此 matInput 的 FormControl 以及父表单,然后返回一个布尔值,指示是否应显示错误.(真的表示应该显示它们,false 表示它们不应该.)
我会制作一个单独的文件,例如 default.error-matcher.ts
/** 当无效控件脏了或被触摸时出错*/导出类 MyErrorStateMatcher 实现 ErrorStateMatcher {isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {return !!(control && control.invalid && (control.dirty || control.touched));}}
然后在TS文件中添加:
matcher = new MyErrorStateMatcher();
然后将输入更改为使用匹配器:
<input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required><mat-error *ngIf="dueDateValidator.invalid">任务需要截止日期</mat-error></mat-form-field>
I am trying to do validation using the <mat-form-field>
and <mat-error>
. This works fine when user tabs out of the input without filling. But how do I force this error to show when I click a button? I am not using submit. Also, using template-driven forms.
This is my code:
HTML:
<mat-form-field>
<input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
<mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
TS:
dueDateValidator: FormControl = new FormControl('', [Validators.required]);
See how to use a form with a custom ErrorStateMatcher
I would make a separate file such as default.error-matcher.ts
/** Error when invalid control is dirty or touched*/
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.dirty || control.touched));
}
}
Then in the TS file add:
matcher = new MyErrorStateMatcher();
Then change the input to use matcher:
<mat-form-field>
<input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required>
<mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
这篇关于角度材料 - 单击按钮时显示垫错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!