Angular2显示所有表单组验证错误

时间:2017-05-23 13:28:19

标签: angular angular2-forms

我正在使用Angular2和FormGroup构建一个深层嵌套表单,目前我有一个表单,例如在父控制器中:

this.orderForm = this.fb.group({

customerSelectForm: this.fb.group({ // create nested formgroup to pass to child
        selectTypeahead: ['', 
                            Validators.required],
        })
})

然后在子组件中我有:

<div class="form-group" [formGroup]="customerSelectForm" *ngIf="customerSelectForm">
        <label for="oh-custaccount">Customer Account #</label>

    <input class="form-control" type="text" 
    formControlName="selectTypeahead"
    (focusout)=someFunction() />

    <p *ngIf="customerSelectForm.controls.selectTypeahead.errors?.required">
    Number required!</p>
</div>

现在这个子模板工作正常,如果文本框中没有输入,则在屏幕上呈现错误。然后我在父控制器中返回一个提交按钮:

<button type="submit" class=" btn btn-success" [disabled]="orderForm?.invalid">Submit</button>

同样,这可以按预期工作,只有在selectTypeahead输入中注册了输入后才会启用。

现在由于这个表单的大型特性,我希望在提交按钮旁边有一个显示,其中列出了当前失败的所有表单元素。我确实试过渲染:

{{orderForm.errors}}

但这仍然是&#34; null&#34;即使我的表单无效,我如何列出orderFrom中当前未通过/匹配相应验证规则的所有输入?

1 个答案:

答案 0 :(得分:8)

我认为您必须以递归方式访问表单的后代控件以获取所有错误。

getAllErrors(form: FormGroup | FormArray): { [key: string]: any; } | null {
    let hasError = false;
    const result = Object.keys(form.controls).reduce((acc, key) => {
        const control = form.get(key);
        const errors = (control instanceof FormGroup || control instanceof FormArray)
            ? this.getAllErrors(control)
            : control.errors;
        if (errors) {
            acc[key] = errors;
            hasError = true;
        }
        return acc;
    }, {} as { [key: string]: any; });
    return hasError ? result : null;
}

然后在你的模板中

<!--
  NOTE: This is just for displaying the result of the method
  You should replace the `<pre><code>` with whatever your snippet is like
-->
<pre><code>{{ getAllErrors(orderForm) | json }}</code></pre>
相关问题