问题描述
以 https://material.angular.io/components/form- 为例字段/概览
<mat-form-field><input matInput placeholder="输入您的电子邮件" [formControl]="email" required><mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error></mat-form-field>从 '@angular/core' 导入 {Component};从@angular/forms"导入 {FormControl, Validators};/** @title 带有错误信息的表单字段 */@成分({选择器:表单字段错误示例",templateUrl: 'form-field-error-example.html',styleUrls: ['form-field-error-example.css']})导出类 FormFieldErrorExample {email = new FormControl('', [Validators.required, Validators.email]);getErrorMessage() {返回 this.email.hasError('required') 吗?'您必须输入一个值':this.email.hasError('email') ?'不是有效的电子邮件':'';}}
错误似乎是在模糊时触发的.只有在离开输入后才会出现错误.在我的应用程序中也是如此.在当前模式下,错误存在,但直到输入失去焦点才显示.
如何在输入更改时触发错误显示.
根据 docs 您需要使用 errorStateMatcher
.
对于你来说,这看起来像这样:
导出类 MyErrorStateMatcher 实现 ErrorStateMatcher {isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {return !!(control && control.invalid && (control.dirty || control.touched));}}
并在您的组件中执行以下操作:
matcher = new MyErrorStateMatcher();
然后只需在您的输入字段中添加
[errorStateMatcher]="matcher"
StackBlitz
Given the example at 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' :
'';
}
}
The error seems to be triggered on-blur. Only after leaving the input does the error appears. It is the same in my application. In this current mode, error exist but the is not displayed until the input loses focus.
How can I trigger the error to be displayed when the input change.
As per the docs you need to use an errorStateMatcher
.
For you that would look like this:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.dirty || control.touched));
}
}
and in your component do:
matcher = new MyErrorStateMatcher();
Then just add in your input field
[errorStateMatcher]="matcher"
StackBlitz
这篇关于如何触发 Material2 <mat-error>在输入更改时显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!