angular 2 formbuilder conditional validating input -
i using angular 2 formbuilder create form , want conditionally validate input field according radio box input changes.when click percentage radio box percentage input should validated. when click amount radio box should validate amount input field.
html code
(i using material input components)
<md-radio-group formcontrolname="splittype" (click)="splittypeclicked()"> <md-radio-button value="amount">amount</md-radio-button> <md-radio-button value="percentage">percentage</md-radio-button> </md-radio-group> <input mdinput placeholder="amount" formcontrolname="amount" > <input mdinput placeholder="percentage" formcontrolname="percentage" >
angular 2 component
constructor(private fb: formbuilder){} ngoninit() { this.splitchargeform = this.fb.group({ splittype: ['', validators.required], amount: [''], //validate when splittype = amount percentage: [''] //validate when splittype = percentage });
write code ngoninit()
method. help
solution 1:
this.splitchargeform.get('splittype') .valuechanges.subscribe((value: string) => { if (value === 'amount') { this.splitchargeform.get('amount').setvalidators(validators.required); this.splitchargeform.get('percentage').clearvalidators() } else { this.splitchargeform.get('percentage').setvalidators(validators.required); this.splitchargeform.get('amount').clearvalidators() } });
solution 2:
// formbuilder
this.splitchargeform = this.fb.group({ splittype: ['', validators.required], amount: [{value: '', disabled: false}, validators.required], percentage: [{value: '', disabled: true}, validators.required] });
// enable & disable input (write in oninit() method or cunstructor)
this.splitchargeform.get('splittype') .valuechanges.subscribe((value: string) => { if (value === 'amount') { this.splitchargeform.get('amount').enable; this.splitchargeform.get('percentage').disable(); } else { this.splitchargeform.get('percentage').enable(); this.splitchargeform.get('amount').disable() } });
html should like
<md-radio-group formcontrolname="splittype" (click)="splittypeclicked()"> <md-radio-button value="amount">amount</md-radio-button> <md-radio-button value="percentage">percentage</md-radio-button> </md-radio-group> <input mdinput placeholder="amount" formcontrolname="amount" *ngif="splitchargeform.value.splittype === 'amount" > <input mdinput placeholder="percentage" formcontrolname="percentage" *ngif="splitchargeform.value.splittype === 'percentage" >
Comments
Post a Comment