角材料-单击按钮时显示垫错误 [英] Angular Material - show mat-error on button click

查看:94
本文介绍了角材料-单击按钮时显示垫错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用<mat-for-field><mat-error>进行验证.当用户从输入中跳出但不填满时,此方法很好用.但是,当我单击按钮时如何强制显示此错误?我没有使用提交.另外,使用模板驱动的表单.

I am trying to do validation using the <mat-for-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.

这是我的代码:

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]);

dueDateValidator: FormControl = new FormControl('', [Validators.required]);

推荐答案

查看如何将表单与自定义

如果您希望覆盖此行为(例如,尽快显示错误 由于无效控件是脏的或父表单组为 无效),则可以使用matInput的errorStateMatcher属性. 该属性采用ErrorStateMatcher对象的实例.一个 ErrorStateMatcher必须实现单个方法isErrorState,其中 接受此matInput的FormControl以及父窗体, 返回一个布尔值,指示是否应显示错误. (真的 指示应显示它们,而false指示应显示它们 不应该.)

If you wish to override this behavior (e.g. to show the error as soon as the invalid control is dirty or when a parent form group is invalid), you can use the errorStateMatcher property of the matInput. The property takes an instance of an ErrorStateMatcher object. An ErrorStateMatcher must implement a single method isErrorState which takes the FormControl for this matInput as well as the parent form and returns a boolean indicating whether errors should be shown. (true indicating that they should be shown, and false indicating that they should not.)

我将创建一个单独的文件,例如default.error-matcher.ts

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));
  }
}

然后在TS文件中添加:

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>

这篇关于角材料-单击按钮时显示垫错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆