gpt4 book ai didi

angular-material2 - 如何触发 Material2 在输入更改时显示

转载 作者:行者123 更新时间:2023-12-04 23:14:05 25 4
gpt4 key购买 nike

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' :
'';
}
}

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

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

最佳答案

根据 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

关于angular-material2 - 如何触发 Material2 <mat-error> 在输入更改时显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com