【问题标题】:How to trigger Material2 <mat-error> to be displayed on input-change如何触发 Material2 <mat-error> 在输入更改时显示
【发布时间】:2019-06-22 14:34:51
【问题描述】:

以https://material.angular.io/components/form-field/overview 为例

<div class="example-container">
  <mat-form-field>
    <input matInput placeholder="Enter your email" [formControl]="email" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>


import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

/** @title Form field with error messages */
@Component({
  selector: 'form-field-error-example',
  templateUrl: 'form-field-error-example.html',
  styleUrls: ['form-field-error-example.css']
})
export class FormFieldErrorExample {
  email = new FormControl('', [Validators.required, Validators.email]);

  getErrorMessage() {
    return this.email.hasError('required') ? 'You must enter a value' :
        this.email.hasError('email') ? 'Not a valid email' :
            '';
  }
}

错误似乎是在模糊时触发的。只有在离开输入后才会出现错误。在我的应用程序中也是如此。在当前模式下,存在错误,但直到输入失去焦点才会显示。

如何在输入更改时触发显示错误。

【问题讨论】:

    标签: angular-material2 angular5


    【解决方案1】:

    根据docs,您需要使用errorStateMatcher。

    对于你来说,看起来像这样:

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

    在你的组件中做:

    matcher = new MyErrorStateMatcher();
    

    然后只需添加您的输入字段

    [errorStateMatcher]="matcher"
    

    StackBlitz

    【讨论】:

    • 能否请您解释一下 [formControl]="email" 在 StackBlitz 中的用途是什么?组件没有公开formControl 属性,而且FormControl 似乎也不是指令。所以我在这里很困惑。
    【解决方案2】:

    在你的组件类中:

    matcher = {
      isErrorState: () => {
        return this.statusField; // return Boolean status value
      }
    };
    

    然后只需添加您的 matInput 字段

    [errorStateMatcher]="matcher"
    

    【讨论】:

    • 这个答案也适用于使用 ngModel 的简单输入
    • 什么是statusField?它不存在
    猜你喜欢
    • 2015-08-15
    • 2021-10-08
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    相关资源
    最近更新 更多