jor*_*l88 7 angular angular-reactive-forms
我正在尝试在角度反应形式上设置条件形式验证,需要一些帮助.
我有一个表单控件,用户将其实体类型设置为Individual或Business
<select formControlName="entity">
<option [value]="individual">Individual</option>
<option [value]="business">Business</option>
</select>
Run Code Online (Sandbox Code Playgroud)
然后我根据选择的实体显示或隐藏表单输入:
<div *ngIf="myForm.controls.entity.value == individual>
<input formControlName="fullName" />
</div>
<div *ngIf="myForm.controls.entity.value == business>
<input formControlName="businessName" />
</div>
Run Code Online (Sandbox Code Playgroud)
如果选择了相应的实体,如何才能使两个输入都需要?
Meh*_*hdi 11
假设此html位于formGroup元素内,您可以使用属性[formControl] ="name_of_your_input_control"
<div [hidden]="isBusiness">
<input [formControl]="fullName" />
</div>
<div [hidden]="!isBusiness">
<input [formControl]="businessName" />
</div>
Run Code Online (Sandbox Code Playgroud)
在你的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
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,我将*ngIf更改为[hidden],因为*ngIf将完全删除模板中的控件,其中[hidden]将仅应用display none.
您还可以在特定控件上添加更改侦听器,而不是整个表单,但想法是相同的.
| 归档时间: |
|
| 查看次数: |
6169 次 |
| 最近记录: |