Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular2显示所有表单组验证错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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>

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

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

同样,这可以按预期工作,并且仅在SELEctTypeahead输入中注册输入后才启用.

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

{{orderForm.errors}}

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

我认为你必须以递归方式访问表单的后代控件以获取所有错误.
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>

大佬总结

以上是大佬教程为你收集整理的Angular2显示所有表单组验证错误全部内容,希望文章能够帮你解决Angular2显示所有表单组验证错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。