首页 > 解决方案 > 如何处理默认的 Angular 表单验证错误?

问题描述

我在这里使用反应式表单验证。我有 3 个字段电子邮件、全名和密码(均为必填项)。当我只需单击任何一个字段并单击关闭字段时。默认情况下,Angular 在字段上显示红色边框

我想在输入字段并删除所有文本并单击外部时显示红色边框。

当我只是单击字段并单击字段时,我不想显示红色边框。

如何覆盖此默认行为?

模板

<form name="form" (ngSubmit)="onSubmit(signUpForm)" #f="ngForm" 
        #signUpForm="ngForm" [formGroup] = "signup"
        fxShow="true" fxFlex fxLayout="column" fxLayoutAlign="center stretch" fxLayoutGap="4px">

        <div>
            <mat-form-field appearance="outline">
                <mat-label>Email</mat-label>
                <input matInput placeholder="Enter the email" name="email" formControlName="email">
            </mat-form-field>
        </div>
        <div>
            <mat-form-field appearance="outline">
                <mat-label>Full Name</mat-label>
                <input matInput placeholder="Enter your fullname" name="fullname" formControlName="fullname">
            </mat-form-field>
        </div>
        <div>
            <mat-form-field appearance="outline">
                <mat-label>Password</mat-label>
                <input matInput placeholder="Enter the password" name="password" formControlName="password">
            </mat-form-field>
        </div>
        <div>
            <button class="btn btn-info height_40" type="submit" [disabled]="signup.invalid" fxFlex="98">
                Sign Up
            </button>
        </div>
    </form>

打字稿文件

export class SignupComponent implements OnInit {

  signup: FormGroup;

  constructor(private formBuilder: FormBuilder) {
      this.signup = formBuilder.group({
        email: ['', Validators.required],
        fullname: ['', Validators.required],
        password: ['', Validators.required]
      })
   }
}

标签: angular

解决方案


如文档中所述:

默认情况下,当控件无效并且用户与之交互(触摸)时会显示这些错误消息

您可以覆盖可以使用自定义errorStateMatcher的行为。通过扩展 ErrorStateMatcher 接口创建自定义 MyErrorStateMatcher。然后将此错误匹配器放在 matInput 元素上,如下所示:

组件.ts

/** Error when control is pristine. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    console.log(control!.touched && control!.dirty); 
    return !control!.pristine;
  } 
} 
matcher = new MyErrorStateMatcher();

组件.html

<input type="email" matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
           placeholder="Ex. pat@example.com">

工作示例


推荐阅读