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
})
};
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>
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.