I have an input field that is required only if another value is set. The other value is from a select. Note, my actual form is much more complicated but here is an example showing the parts that are pertinent to this question:
the template:
<form name="createPaymentForm" (ngSubmit)="f.form.valid && createPayment()" #f="ngForm" novalidate>
<select name="orderNumberType" #orderNumberType="ngModel"
[(ngModel)]="payment.orderNumberType">
<option [ngValue]="undefined" disabled>Select</option>
<option *ngFor="let opt of paymentIdOptions" [value]="opt.id">{{opt.label}}</option>
</select>
<div [ngClass]="{ 'has-error': f.submitted && !orderNumber.valid }">
<input type="text" name="orderNumber"
[(ngModel)]="payment.orderNumber" #orderNumber="ngModel">
</div>
</form>
the component:
import { Component, OnInit } from '@angular/core';
import { PaymentsService } from '../../../services/payments.service';
import { Payment } from '../../../models';
@Component({
selector: 'app-new-payment',
templateUrl: './new-payment.component.html',
styleUrls: ['./new-payment.component.scss']
})
export class NewPaymentComponent implements OnInit {
paymentIdOptions: any = [];
payment: Payment = {};
constructor( private paymentsService: PaymentsService ) { }
ngOnInit() {
this.paymentsService.getOrderNumberTypes().subscribe(orderNumberTypes => {
this.paymentIdOptions = orderNumberTypes;
});
}
createPayment() {
console.log(this.payment);
//do something...
}
}
My goal is to only require the orderNumber if the orderNumberType is set to any value other than 'undefined'. What is the easiest way to implement this?
(Note, Angular 5)