angular 2 formbuilder条件验证输入

时间:2017-07-26 05:18:13

标签: angular angular2-formbuilder reactive-forms

我正在使用angular 2 formbuilder来创建表单,我想根据单选框输入更改有条件地验证输入字段。当我单击百分比单选框时,应验证百分比输入。当我点击金额单选框时,它应该验证金额输入字段。

HTML代码

(我正在使用材料输入组件)

<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

   });

1 个答案:

答案 0 :(得分:6)

将此代码写入ngOnInit()方法。这有帮助

解决方案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()
        }
    });

解决方案2:

// formBuilder

  this.splitChargeForm = this.fb.group({
      splitType: ['', Validators.required],
      amount: [{value: '', disabled: false}, Validators.required], 
      percentage: [{value: '', disabled: true}, Validators.required]
   });

// enable&amp;禁用输入(写入onInit()方法或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应该像

<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" >