2

我正在使用 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 组件

constructor(private fb: FormBuilder){}
   
  ngOnInit() {

    this.splitChargeForm = this.fb.group({
      splitType: ['', Validators.required],
      amount: [''],        //validate when splitType = amount
      percentage: ['']     //validate when splitType = percentage

   });
4

1 回答 1

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:

// 表单构建器

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

// 启用和禁用输入(写入 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" >
于 2017-07-26T05:53:39.527 回答