我正在使用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}}
但即使我的表单无效,这仍然是“空”,我如何列出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>