隐藏字段上的Angular 2表单验证

Haz*_*ari 6 javascript forms validation angular

我有一个银行贷款应用程序,该应用程序由很多输入字段组成,其中一些输入字段是隐藏的(这些隐藏字段根据一组竞争条件动态显示)。例如,如果您选择选项1,则会显示一个隐藏字段,而其他一些字段则被隐藏。如果选择选项2,则显示某些字段,而隐藏其他字段。在表单的最后,我有一个,这意味着在整个表单有效之前,该按钮将被禁用,但是我现在的问题是隐藏字段也得到了验证,因此该表单将永远无效。有没有一种方法可以告诉angular如果隐藏字段则不验证它们?

我隐藏字段的方式类似于以下示例:

<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>
Run Code Online (Sandbox Code Playgroud)

viv*_*ien 10

您正在使用反应式形式。即使字段对用户隐藏,字段在 from 中也处于活动状态。因此,您只需使用以下代码从反应中禁用该字段

form.get("fieldName").disable();
Run Code Online (Sandbox Code Playgroud)

在反应形式中,您不需要输入标签中的“必需”。还要添加 formControlName 如下。

<input formControlName="inputFieldName" type="text">
Run Code Online (Sandbox Code Playgroud)

所以html文件会像

<form [formGroup]="form" novalidate>

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

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

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

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

</form>
Run Code Online (Sandbox Code Playgroud)

我们将 formControlName 添加到 2 个输入字段,并在 ts 文件中声明。

this.form = this.formBuilder.group({
    loanType: ["", [Validators.required]],
    inputField1: ["", [Validators.required]],
    inputField2: ["", [Validators.required]],
});
Run Code Online (Sandbox Code Playgroud)

我们可以为 LoanType 字段创建值更改侦听器

this.form.get("loanType").valueChanges.subscribe((loanType) => {
    this.form.get("inputField1").disable();
    this.form.get("inputField2").disable();
    if(loanType === 1) {
         this.form.get("inputField1").enable();
    } else if (loanType === 2) {
         this.form.get("inputField2").disable();
    }
});
Run Code Online (Sandbox Code Playgroud)

因此,当贷款类型为 1 时,将启用 inputField1,而当贷款类型为 2 时,将启用 inputField2。

当字段被隐藏时,此表单将有效,因为它被禁用。


Haz*_*ari 6

更新:

经过一些研究,我发现我需要通过使用FormGroup.addControl()和FormGroup.removeControl()动态更新formGroup。

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

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

只是举一个例子,说明我的代码对于下一个有同样问题的男人的样子:

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