角度无效表单的条件表单验证
我试图在角度无效表单上设置条件表单验证并需要一些帮助。角度无效表单的条件表单验证
我有其中用户将他们的实体类型到个人或商业
<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” 假设这个网站是一个formGroup元素
<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]只会应用显示没有。
您也可以在特定的控件上添加更改侦听器,而不是整个表单,但这个想法是相同的。
或者您可以在运行时定义您的控件: isBusiness:boolean = false; //... this.nameOfYourForm.valueChanges.subscribe((newForm) => { this.isBusiness = (newForm.controls.entity.value == 'business'); if(this.isbusiness){ this.nameOfYourForm.registerControl('yourControl', new FormControl('', [Validators])); }else{ this.nameOfYourForm.removeControl('yourControl'); })
–
我有一个其他版本:
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>
的可能的复制[角2:在某些条件应用Validator.required验证](HTTPS://计算器.com/questions/42238639/angular-2-apply-validator-required-validation-on-some-condition) – JayChase