angular - 为什么 mat-error 不会在带有自定义全局验证器的 Angular Material 6 中的 mat-form 字段中显示

标签 angular angular-material2 angular6 angular-material-6

我正在使用 Angular Material 6,我在 mat-form-field 中有一个验证,当在 mat-form-field 之后移动到正确显示的 mat-error 时,mat-error 未显示。

无效代码:

 <mat-form-field>
<input matInput type="time" formControlName="ToTime"/> <mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>
     </mat-form-field>

工作正常:

 <input matInput type="time" formControlName="ToTime"/> </mat-form-field>
 <mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>

有人解释了为什么 which 在该控件内不起作用。

现场演示: stackblitz

最佳答案

是的,mat-error 默认不显示。它仅在输入被触摸时显示。

但是,幸运的是,您可以使用绑定(bind)到 mat-input 元素的 errorStateMatcher 输入属性覆盖此行为。

pull request其中添加了此功能。

用法:

<mat-form-field>
    <input matInput [errorStateMatcher]="matcher" [matDatepicker]="picker" placeholder="Choose a Start date" 
    formControlName="FromDate"
      [min]="minFromDate" 
           [max]="maxToDate" >
    <mat-datepicker-toggle matSuffix [for]="picker" ></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
    <mat-error >Please provide a valid Fromdate</mat-error> 
  </mat-form-field> 

所以你必须以这种方式在你的代码中实现 ErrorStateMatcher

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return (control && control.invalid);
  }
}

然后在您的组件中为 ErrorStateMatcher 类添加一个新对象 matcher,它将充当 [errorStateMatcher]="matcher"

matcher = new MyErrorStateMatcher();

我还在你的 fork stackblitz 中添加了相同的代码

建议:

您无需为指定formControlNamemat-error 提供ngIf 条件。系统会根据它所在的 mat-form-field 自动考虑它。

关于angular - 为什么 mat-error 不会在带有自定义全局验证器的 Angular Material 6 中的 mat-form 字段中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456487/

相关文章:

javascript - 如何在按钮单击时有条件地以 Angular 加载组件

Angular Material 自定义表单字段控件的值未在调用 FormGroup 中更新

Angular Material 2 主题在生产中不起作用

angular6 - "AngularCli"在 "Microsoft.AspNetCore.SpaServices"命名空间中不存在

node.js - 在 typescript 中使用带有 Angular 6 的 Node 短 ID 模块

javascript - 获取空的json数据

angular - 如何从组件触发 Angular 2 表单提交?

css - angular-flex-layout:fxLayoutWrap 将 ... 附加到不适合的文本,而不是将文本换行到下一行

node.js - 无法扩展接口(interface) 'http.IncomingMessage' 。你的意思是 'implements' 吗?

angular - Angular Material 2 中的 md 表