st_*_*rke 4 angular-material2 angular5
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' :
'';
}
}
Run Code Online (Sandbox Code Playgroud)
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.
根据文档,您需要使用errorStateMatcher。
对于您来说,看起来像这样:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.dirty || control.touched));
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的组件中执行以下操作:
matcher = new MyErrorStateMatcher();
Run Code Online (Sandbox Code Playgroud)
然后只需在您的输入字段中添加
[errorStateMatcher]="matcher"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10966 次 |
| 最近记录: |