我按照 angular angular form validation error example 的建议方法显示 react 形式的错误消息.

页面显示错误的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)]] 
    }) 

如果你看到上面的代码,我已经对我的 firstName 和 lastName 字段应用了两个验证。

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

有没有最好的方法在不编写多个 *ngIf 条件的情况下显示特定控件的验证消息?

请您参考如下方法:

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

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

打印error.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; 
 
} 

打印error.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> 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!