隐藏字段上的Angular 2表单验证 [英] Angular 2 form validation on hidden fields

查看:89
本文介绍了隐藏字段上的Angular 2表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个银行贷款申请,其中包含很多输入字段,其中一些是隐藏的(隐藏字段是根据一组条件动态显示的)。例如,如果选择选项1,则会显示隐藏字段,并隐藏其他一些字段。如果选择选项2,某些字段将显示,其他字段将隐藏。在表单的最后我有一个意味着按钮将被禁用,直到整个表单有效,但我现在的问题是隐藏字段也得到验证,因此表单将永远无效。有没有办法告诉角度如果它们被隐藏则不验证字段?

I have a bank loan application which consists of alot of input fields, some of which are hidden (the hidden fields are shown dynamically based on a set of contidions). E.g if you choose option 1, a hidden field gets shown, and some other fields are hidden. If you choose option 2, some fields gets show, other fields get hidden. In the end of the form i have a which means the button will be disabled until the whole form is valid, but my problem now is that the hidden fields also get validated so the form will never be valid. Is there a way to tell angular to not validate fields if they are hidden?

我隐藏字段的方式如下例所示:

The way i hide my fields is like the example below:

<form [formGroup]="form">

<select formControlName="loanType"> 
 <option value="0">Car loan</option>
 <option value="1">Student loan</option>
</select>

<div *ngIf="loanType === 0"> 
 <input type="text" required>
</div>

<div *ngIf="loanType === 1">
 <input type="text" required>
</div>

<button type="submit" [disabled]="!form.isValid">

</form>


推荐答案

更新:

在做了一些研究之后,我发现我需要使用FormGroup.addControl()和FormGroup.removeControl()动态更新formGroup。

After doing some research, i found that i need to dynamically update the formGroup by using FormGroup.addControl() and FormGroup.removeControl().

我读到的文章得出的结论是:
https://github.com/angular/angular/issues/7970 (查看Karas答案)

The articles i read to come to my conclusion was: https://github.com/angular/angular/issues/7970 (check Karas answer)

https://scotch.io/tutorials/how -to-implement-conditional-validation-in-angular-2-model-driven-forms

只是举例说明我的代码是什么样的对于具有相同问题的下一个人:

just to give an example of what my code looks like for the next man with the same problem:

if (this.loanTypeId === 1) {
   this.form.addControl('name', new FormControl("", Validators.required));
} else {
   this.form.removeControl('name')
}

这篇关于隐藏字段上的Angular 2表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆