首页 文章

角度反应形式的条件形式验证

提问于
浏览
3

我正在尝试在角度反应形式上设置条件形式验证,需要一些帮助 .

我有一个表单控件,用户将其实体类型设置为Individual或Business

<select formControlName="entity">
  <option [value]="individual">Individual</option>
  <option [value]="business">Business</option>
</select>

然后我根据选择的实体显示或隐藏表单输入:

<div *ngIf="myForm.controls.entity.value == individual>
  <input formControlName="fullName" />
</div>

<div *ngIf="myForm.controls.entity.value == business>
  <input formControlName="businessName" />
</div>

如果选择了相应的实体,如何才能使两个输入都需要?

2 回答

  • 2

    假设此html位于formGroup元素内,您可以使用属性[formControl] =“name_of_your_input_control”

    <div [hidden]="isBusiness">
      <input [formControl]="fullName" />
    </div>
    
    <div [hidden]="!isBusiness">
      <input [formControl]="businessName" />
    </div>
    

    在你的ts类中:

    创建表单后添加以下内容:

    isBusiness:boolean = false;
    //...
    this.nameOfYourForm.valueChanges.subscribe((newForm) => {
         this.isBusiness = (newForm.controls.entity.value == 'business');
         if(this.isbusiness){
            this.nameOfYourForm.controls.fullName.setValidators(/*your new validation here*/);
               //set the validations to null for the other input
         }else{       
               this.nameOfYourForm.controls.businessName.setValidators(/*your new validation here*/);
               //set the validations to null for the other input
         } 
    });
    

    请注意,我将* ngIf更改为[hidden],因为* ngIf将完全删除模板中的控件,其中[hidden]将仅应用display none .

    您还可以在特定控件上添加更改侦听器,而不是整个表单,但想法是相同的 .

  • 7

    我有另一个版本:

    HTML

    <select #select formControlName="entity">
      <option  [ngValue]="Individual">Individual</option>
      <option  [ngValue]="Business">Business</option>
    </select>
    <br>
    <div *ngIf="select.value[0]  === '0'">
      <input #input [required]="select.value[0] === '0'" formControlName="fullName" />
      <span *ngIf="!myForm.get('fullName').valid">Invalid</span>
    </div>
    

    DEMO

相关问题