Angular 响应式表单的条件表单验证

Conditional Form Validations for Angular Reactive Form

我正在尝试在 angular 反应式表单上设置条件表单验证,需要一些帮助。

我有一个表单控件,用户可以在其中将其实体类型设置为个人或企业

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

只有在选择了相应的实体时,如何才能使两个输入都成为必填项?

您可以使用属性 [formControl]="name_of_your_input_control" 假设此 html 在 formGroup 元素中

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

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

在你的 ts class :

创建表单后添加:

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] 将仅应用显示 none。

您也可以在特定控件而不是整个表单上添加更改侦听器,但思路是一样的。

我有另一个版本:

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

RXJS 是 angular 响应式表单的重要组成部分。 ReactiveForms 对这个问题有一个优雅的解决方案。


const formGroup= new FormGroup({
    type: new FormControl(), 
    businessForm: new FormGroup({
      businessName: new Formcontrol('')
    }), 
    individualForm:new FormGroup({
      individualName: new Formcontrol('')
    })
}); 

formType$ = this.formGroup.controls['type'].valueChanges; 

<form [formGroup]="formGroup">

   <div formGroupName="businessForm" *ngIf="(formType$ | async) =='business'">       
     <input formControlName="businessName"/>
   </div>

   <div formGroupName="individualForm" *ngIf="(formType$ | async) =='individual'">
     <input formControlName="individualName"/>
   </div>

</form>