Manoj Sanjeewa Manoj Sanjeewa - 3 years ago 205
Javascript Question

angular 2 formbuilder conditional validating input

I am using angular 2 formbuilder to create a form and I want to conditionally validate the input field according to radio box input changes.when I click percentage radio box the percentage input should be validated. When I click amount radio box it should validate amount input field.

HTML Code



(I am 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

});

Answer Source

write this code into onNgInit() method. does this 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

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 be 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" >
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download