【问题标题】:How do I force the display of validation errors?如何强制显示验证错误?
【发布时间】:2020-03-10 09:38:59
【问题描述】:

我有一个非常标准的材料形式,一切都很甜蜜。

当我提交我的表单时,我有选择地得到验证错误,我循环遍历这些匹配到控件的键,然后设置验证错误。像这样去掉循环。

我真的不认为这很重要,但这里是相关的部分。

 const control = this.form.get(key);
 if (control) {
     control.setErrors({
         server: response.validationErrors[key]
     },{
         emitEvent: true
     });

     // I was trying things like
     // control.markAsTouched() but it did nothing
 }

此时,我的表单正在显示红色字段,这很棒。

但在我与该字段交互之前它不会显示错误消息,这很烦人。

但是,可能导致这种情况的原因是我没有使用<form (submit)="onSubmit(model)"> 语法。因此在我的按钮上我没有使用type=submitattr.form="my-form"

因此,传统上绝不会提交表单。我相信这可能是这里的一个问题。

如果我阅读了Form Field Docs 的材料。它告诉我:

错误消息可以通过添加下划线显示在表单字段下方 表单字段中的 mat-error 元素。最初隐藏错误 并且会在用户设置后显示在无效的表单域上 与元素交互或父表单已提交。

注意到最后一行了吗?我发现很难正确理解它。

问题:

是否有一种机制可以让我在没有交互的情况下立即强制显示这些验证错误?

【问题讨论】:

  • 是的,这是角材质的默认行为,但是你可以编写一个错误状态匹配器来实现你想要的:material.angular.io/components/input/…
  • 一般来说,一个简单的this.form.markAllAsTouched() 必须是可行的,顺便说一句,试试markAsTouched() before setErrors 或用setTimeout 括起来setTimeout(()=>{control.markAsTouched()}

标签: angular angular-material2


【解决方案1】:

看看这个StackBlitz link

这是您的 html 模板文件... [errorStateMatcher]="matcher" 很重要。

<form class="example-form">
    <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
       [errorStateMatcher]="matcher">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
          Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
          Email is <strong>required</strong>
    </mat-error>
   </mat-form-field>
 </form>

在你的 ErroStateMatcher 类文件中..

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2012-08-24
    • 1970-01-01
    • 2012-01-03
    相关资源
    最近更新 更多