3

我想简化下面的代码:

<div *ngIf="form1.errors?.checkDate && (form1.touched || form1.dirty)" class="cross-validation-error-message alert alert-danger">
    Date can't be in the future.
</div>
<div *ngIf="form1.errors?.notAfterDate && (form1.touched || form1.dirty)" class="cross-validation-error-message alert alert-danger">
    Birth Date must be after 1/1/1800.
</div>

它应该只有 1div *ngif并将错误消息作为值传递,而不是硬编码或使用ngFor?

非常感谢您对此的任何帮助。谢谢。

4

2 回答 2

3

管理多个 Angular 表单验证消息的常用技术是将它们存储在地图中。

public validationMessages = {
  'firstName': [
    { type: 'required', message: 'First Name is required' },
    { type: 'maxlength', message: 'First Name may only contain 5 characters.' }
  ],
  'lastName': [
    { type: 'required', message: 'Last Name is required' },
    { type: 'pattern', message: 'Last Name may not be "Smith".' }
  ],
  'email': [
    { type: 'required', message: 'Email is required' },
    { type: 'email', message: 'Enter a valid email' }
  ]
}

HTML 模板

在模板中,用于NgFor遍历所需表单控件的验证消息。

<label>
  Email:
  <input type="email" autocomplete="email" formControlName="email" required>
</label>
<!-- Validation Errors -->
<div *ngFor="let validation of validationMessages.email">
  <div *ngIf="profileForm.get('email').hasError(validation.type) && (profileForm.get('email').dirty || profileForm.get('email').touched)">
    <small style="color:red;">{{validation.message}}</small>
  </div>
</div>

例子

Stackblitz Demo

于 2019-08-31T21:59:17.803 回答
0

我喜欢有一个错误组件。

@Component({
  selector: 'app-error',
  template: `
  <small class="form-text text-danger" *ngIf="(control.touched || control.dirty)
         && control.invalid && (error?control.errors[error]:true)" >
       <ng-content></ng-content>
    </small>`
})
export class ErrorComponent {

  @Input('controlName') controlName: string;
  @Input('error') error: string

  @Input('control') control:any

  visible: boolean = false;

  constructor(@Optional() @Host() public form: FormGroupDirective) { }

  ngOnInit() {
    if (this.form) {
      this.control = this.form.form.get(this.controlName) as FormControl
    }
  }
}

可以在一个formGroup中使用,使用controlNameinput来表示控件,error如果有多个Validator并且想要区分,则使用input

<form [formGroup]="form">
  <input formControlName="email">
    <app-error controlName="email" error="required">Email required.</app-error>
    <app-error controlName="email" error="email">incorrect email </app-error>
</form>

form=new FormGroup({
    email:new FormControl('',[Validators.required,Validators.email])
  })

或独立,使用[control]输入来指示控件

<input [formControl]="control">
<app-error [control]="control">control required</app-error>

control=new FormControl('',Validators.required)

查看stackblitz 演示

于 2019-09-01T09:16:13.723 回答