不带* ngIf的表单验证。我如何在不创建新div的情况下使用表单验证(来自服务)

时间:2018-11-13 10:40:45

标签: angular

如何使用表单验证(来自服务),而不必每次都创建新的div来验证Error.Eg:

<div class="row">
  <div class="form-group col-md-2 ">
    <label for="validity" class="input-heading ">Validity*</label>
  </div>
  <div>
    <p ngIf="myForm.get('validity').invalid">Please provide Validity</p>
  </div>

  <div class="form-group col-md-2">
    <div class="row">
      <label for="startMonth" class="input-heading col-md-2">StartMonth</label>
    </div>
    <div class="row">
      <input type="text" class=" from-control">
    </div>
  </div>
  <div class="form-group col-md-2">
    <div class="row">
      <label for="endMonth" class="input-heading col-md-2">EndMonth</label>
    </div>
    <div class="row">
      <input type="text" class=" from-control">
    </div>
  </div>
</div>

-重复代码

<p *ngIf="myForm.get('endMonth').invalid >Please provide End Month</p>
</div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以通过创建一个组件print-error来避免这种补充,该组件将control用作input

print-error.ts

到目前为止,只有一个@Input,但是如果您想进一步自定义,则可以在此处添加更多@Input

import {Component, Input, OnInit, OnDestroy} from '@angular/core';
import {DragulaService} from 'ng2-dragula';

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

    @Input("control")
    private control: any;

}

print-error.html

在此处添加所有类型的验证。它将相应地应用错误消息。

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

</div>

用法

  <input required name="subject" #subject="ngModel" [(ngModel)]="subject">
  <print-error [control]="subject"></print-error>