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

Tas*_*iha 6 angular-material angular-material2 angular6

我想在用户开始在输入元素上写东西后显示 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>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

Sad*_*han 11

你可以这样做 -

<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>
Run Code Online (Sandbox Code Playgroud)

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

onChange($event, password){
    this.model.password = $event;
    if(!password.control.touched){
      password.control.markAsTouched();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这确实达到了目的。但我不明白为什么我应该发送事件参数并从 component.ts 文件中绑定它?因为它已经使用 ngModel 绑定了。有什么理由这样做吗? (3认同)

Chr*_*ian 7

这会将新的匹配器应用到您的整个应用程序:

脏错误状态.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));
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序模块.ts

import { DirtyErrorStateMatcher } from 'your-path-here';
import { ErrorStateMatcher } from '@angular/material/core';
    
@NgModule({
...
  providers: [{
    provide: ErrorStateMatcher,
    useClass: DirtyErrorStateMatcher
  }]
})
Run Code Online (Sandbox Code Playgroud)

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

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