如何使用表单验证(来自服务),而不必每次都创建新的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>
答案 0 :(得分:0)
您可以通过创建一个组件print-error
来避免这种补充,该组件将control
用作input
。
到目前为止,只有一个@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;
}
在此处添加所有类型的验证。它将相应地应用错误消息。
<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>