首页 > 解决方案 > 显示角度反应形式的错误消息的最佳方法,一个表单控制多个验证错误?

问题描述

我根据 angular angular form validation error example的建议方法显示反应式错误消息。

在页面上显示错误的html代码:

<div [formGroup]="myForm">
  <div>
<input type="text" formControlName="firstName"/>
<div *ngIf="myForm.controls.firstName.invalid"
    class="alert alert-danger">
    <div *ngIf="myForm.controls.firstName.errors.required">
      This Field is Required.
    </div>
    <div *ngIf="myForm.controls.firstName.errors.maxlength">
      your can enter only 50 characters
    </div>
</div>
  </div>
  <div>
<input type="text" formControlName="lastName"/>
<div *ngIf="myForm.controls.lastName.invalid"
    class="alert alert-danger">
    <div *ngIf="myForm.controls.lastName.errors.required">
      This Field is Required.
    </div>
    <div *ngIf="myForm.controls.lastName.errors.maxlength">
      your can enter only 50 characters
    </div>
</div>
  </div>
  </div>

仅供参考我的组件代码如下:

this.myForm = this.formBuilder.group({
      firstName:['',[Validators.required,Validators.maxLength(50)]],
      lastName:['',[Validators.required,Validators.maxLength(50)]]
    })

如果您看到上面的代码,我已经对我的名字和姓氏字段应用了两个验证。

为了显示错误消息,我编写了多个 *ngIf 条件来显示错误消息。

有没有最好的方法来显示特定控件的验证消息而无需编写多个 *ngIf 条件?因为我一次又一次地使用不同的控件名称和验证器名称编写相同的代码来显示错误消息。

标签: angularangular-ng-ifangular-validation

解决方案


我建议有一个print-error可以处理任何类型的 OOTB 或自定义错误的组件。

您可以处理任意数量的错误。

打印错误.component.ts

import {Component, Input} from '@angular/core';

@Component({
    selector: 'print-error',
    templateUrl: './print-error.component.html',
    providers: []
})
export class PrintError {

    @Input("control")
    control: any;

}

打印错误.component.html

<div class="text-danger" *ngIf="control && control.errors && (control.dirty || control.touched)">
     <div *ngIf="control.errors.required"><small>This field is required</small></div>
     <div *ngIf="control.errors.unique"><small>{{control.errors.unique}}</small></div>
     <div *ngIf="control.errors.lessThen"><small>{{control.errors.lessThen}}</small></div>
     <div *ngIf="control.errors.greaterThan"><small>{{control.errors.greaterThan}}</small></div>
     <div *ngIf="control.errors.email"><small>{{control.errors.email}}</small></div>
     <div *ngIf="control.errors.mobile"><small>{{control.errors.mobile}}</small></div>
     <div *ngIf="control.errors.confirmPassword"><small>{{control.errors.confirmPassword}}</small></div>
</div>

用法

 <label for="folder-name">Email</label>
 <input name="email" required   emailValidator #email="ngModel" [(ngModel)]="user.email">
 <print-error [control]="email"></print-error>

推荐阅读