一旦文本框变脏并且处于焦点,如何显示 mat-error?

How to show mat-error once the textbox is dirty and is on focus?

我想在用户开始在输入元素上写东西后立即显示 mat-error。以下是我的代码:

<mat-form-field appearance="outline">
    <mat-label>Password</mat-label>
    <input matInput type="password" placeholder="Password" required [(ngModel)]='model.password' #password='ngModel' name='Password' [minlength]='requiredLength' [pattern]="passwordPattern">
    <mat-error *ngIf="password.errors?.pattern">
        Password must be 8 characters long, one numeric, one special character....
    </mat-error>
</mat-form-field>

我想在用户开始输入时显示错误消息。目前该错误显示在文本框失去焦点上。我也尝试过以下方式:

<mat-error *ngIf="password.dirty">
    <mat-error *ngIf="password.errors?.pattern">
        Password must be 8 characters long, one numeric, one special character....
    </mat-error>
</mat-error>

但这也会产生与以前相同的行为。 一种可能的解决方法可能是使用 mat-h​​int。但我不想根据要求将其显示为提示,我需要将其显示为错误。

顺便说一下,我正在使用 ng-form。

是否可以通过在 ng-form 上使用 mat-error 来获得指定的行为?或者我需要为 mat-h​​int 自定义 css 以使其看起来像错误消息?

如果您想在用户每次击键时触发验证,您必须使用一些变通方法。我建议您使用 FormControl,这样您就可以直接在该控件上设置验证器,还可以监听 valueChanges 发出的更改以将 FormControl 标记为已触及以触发验证(也许有更好的解决方案?)。

见下文stackblitz。验证通过 Validators.pattern(最少 8 个字符,至少一个字母、一个数字和一个特殊字符)完成,因此不再需要必需或最小长度验证器。

你可以这样做 -

<mat-form-field appearance="outline">
  <mat-label>Password</mat-label>
  <input matInput 
        type="password"
        placeholder="Password"
        name='Password'
        [ngModel]='model.password'
        (ngModelChange)="onChange($event, password)"
        #password='ngModel'
        [minlength]='requiredLength'
        [pattern]="passwordPattern"
        required>
  <mat-error *ngIf="password.errors?.pattern"">
      Password must be 8 characters long, one numeric, one special character....
  </mat-error>
</mat-form-field>

并在您的 component.ts 中添加 onChange() 方法 -

onChange($event, password){
    this.model.password = $event;
    if(!password.control.touched){
      password.control.markAsTouched();
    }
}

这会将新的匹配器应用于您的整个应用:

脏错误-state.matcher.ts

import {FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

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

app.module.ts

import { DirtyErrorStateMatcher } from 'your-path-here';
import { ErrorStateMatcher } from '@angular/material/core';

@NgModule({
...
  providers: [{
    provide: ErrorStateMatcher,
    useClass: DirtyErrorStateMatcher
  }]
})

2021 年 1 月 2 日由 Reza Taba 更新:

添加了 control.touched,因此如果用户离开该字段时没有值,则会出现 required 错误。