使用验证器的Angular 2表单验证,该元素使用* ngIf动态构建 [英] Angular 2 Form Validation Using Validators WIth An Element That Is Dynamically Built Using *ngIf

查看:65
本文介绍了使用验证器的Angular 2表单验证,该元素使用* ngIf动态构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,并且正在使用反应式表格进行验证.我可以使所有验证工作,除了我有条件地提供了一些输入,即使没有使用* ngIf将其提供给视图,这些输入仍使表单无法进行验证.仅当条件为真时才可以说"Validators.required".请参见示例.

I have a form and am using Reactive Forms for validation. I can get all the validation to work EXCEPT I have some inputs that are served conditionally that are still keeping the form from validating even when they are not served to the view using *ngIf. How can I say "Validators.required" only if a condition is true. Please see example.

constructor(
    private QRService:QRService,
    fb: FormBuilder
    ){
    this.title = 'My Form';
    this.showDeliveryTypes = false;
    this.complexForm = fb.group({
      'itemnumber' : [null, Validators.required],
      'dateofbirth' : [null, Validators.required],
      'deliverytype' : [null, Validators.required],
      'pickuplocation' : [null, Validators.required], //validates even if these aren't included using *ngIf
      'paymentoptions' : [null, Validators.required] //validates even if these aren't included using *ngIf
   })

};

如果* ngIf在表单中包含取货地点或付款方式,我只想验证它们.

I only want to validate pickuplocations or paymentoptions if the *ngIf includes them in the form.

<form [formGroup]="complexForm" (ngSubmit)="findScript(complexForm.Form)">
  <h2>Script Number</h2>
  <input type="number" name="script" [(ngModel)]="itemno" (blur)="getScripts(itemno)" [formControl]="complexForm.controls['itemnumber']">
  <h2>Date of birth</h2>
  <input type="date" name="dob" [(ngModel)]="dateofbirth" (blur)="getScripts(scriptno, dateofbirth)" [formControl]="complexForm.controls['dateofbirth']" required>
  <div *ngIf="showDeliveryTypes" name="deliverytypes">
  <h3>Delivery Method</h3>
  <select #select [(ngModel)]="selectedId" (change)="validateDeliveryTypes(select.value)" name="deliveryoptions" [formControl]="complexForm.controls['deliverytype']">
    <option *ngFor="let item of qrData.DeliveryTypes" [value]="item.DeliveryTypeId">{{item.DeliveryTypeName}}</option>

  </select>
  </div>
  <div *ngIf="showPickupLocations" name="pickuptypes">
  <h3>Pickup Locations</h3>  //I don't want to validate these UNLESS the *ngIf is true
  <select #select [(ngModel)]="selectedPickupId" (change)="checkVals(select.value)" name="pickupoptions" [formControl]="complexForm.controls['pickuplocation']">
    <option *ngFor="let item of selectedItem.PickupLocations" [value]="item.PickupLocationId">{{item.PickupLocationName}}</option>

  </select>
  </div>
  <div *ngIf="showPaymentOptions" name="paymentoptions">
  <h3>Payment Types</h3>  //I don't want to validate these UNLESS the *ngIf is true
  <select #select [(ngModel)]="selectedPayment" (change)="checkVals(select.value)" name="selectpaymentoptions" [formControl]="complexForm.controls['paymentoptions']">
    <option *ngFor="let item of selectedItem.PaymentTypes" [value]="item.PaymentTypeId">{{item.PaymentTypeName}}</option>

  </select>
  </div>
  <button (click)="findScript()" type="submit" name="submitbutton" [disabled]="!complexForm.valid">Find Prescription</button>
</form>

我对Angular2还是很陌生,可以在Angular 1中轻松地做到这一点,但我真的很想在将来的开发中迁移到Angular2.

I'm still fairly new to Angular2 and can do this easily in Angular 1, but really wanting to move to Angular2 with future development.

推荐答案

一种方法是在从DOM中隐藏表单字段时禁用它.禁用表单控件,将表单字段完全从表单中排除,这就是您想要的.如果确实需要在提交时获取包含在表单中的值,则可以使用方法getRawValue.但是否则,表单字段将被完全排除.

One way would be to disable the form field when you are hiding it from the DOM. Disabling the form control, excludes that form field from the form entirely, which is what you want. If you do need to get the value included in your form upon submit, you can use the method getRawValue. But otherwise the form fields will be excluded entirely.

由于您的表单非常复杂,因此我为您设置了一个简单的示例代码和插件,我们在其中禁用了姓氏并将其从DOM中删除.

Since your form is pretty complex, I have set up a simple example code and plunker for you, where we disable lastname and remove it from the DOM.

由于不知道如何切换showPickupLocationsshowPaymentOptions,因此我仅在此处使用一个按钮来切换姓氏的可见性.因此,表单如下所示:

Since not knowing how you toggle the showPickupLocations and showPaymentOptions, I'll just use a button here, which toggles the visibility of lastname. So the form would look like this:

<button (click)="toggle()">Toggle lastname</button>
<form [formGroup]="myForm">
  <label>firstname: </label>
  <input formControlName="firstname"/>
  <div *ngIf="toggl">
     <label>lastname: </label>
     <input formControlName="lastname"/>
  </div>
</form>

当我们在DOM中切换姓氏可见性时,我们还会切换启用和禁用formfield:

And when we toggle lastname visibility in DOM, we also toggle the enabling and disabling of the formfield:

toggle() {
  this.toggl = !this.toggl;
  let control = this.myForm.get('lastname')
  control.enabled ? control.disable() : control.enable()
}

如前所述,这从表单中排除了该字段,因此验证不会成为问题.在此演示插件中,您可以看到切换如何从表单值中完全删除lastname字段.

As said, this excludes the field from the form, so validation will not be a problem. In this demo plunker you can see how the toggling removes the lastname field from the form values entirely.

这篇关于使用验证器的Angular 2表单验证,该元素使用* ngIf动态构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆