Angular嵌套FormGroup中hasError访问内层FormControl校验方案
嵌套Angular表单校验方法改造方案
原hasError方法仅支持查找最外层表单控件,传入person.nameC不生效的核心原因是方法直接将传入的字符串作为单层key匹配最外层controls,没有解析嵌套路径。直接用Angular表单自带的路径获取能力改造即可,不需要手写复杂的遍历逻辑。
推荐实现:利用FormGroup原生get方法
Angular的AbstractControl.get()原生支持点分隔的嵌套路径字符串,不管多少层嵌套表单都能直接定位控件,改造代码最少:
public hasError = (controlPath: string, errorName: string) => { const targetControl = this.prozessPersonenzuordnungenForm.get(controlPath); // 增加空值兜底,避免路径错误或控件未初始化时报错 return !!targetControl && targetControl.hasError(errorName); };
模板中调用时传入完整的点分隔路径即可:
<mat-error *ngIf="hasError('person.nameC', 'required')">Bitte gebe eine Person an!</mat-error>
这种实现支持任意层级的嵌套,哪怕后续表单加了三层、四层嵌套结构,比如person.address.street这种路径,方法不需要任何修改就能直接用。
可选实现:指定分组参数(适合固定层级场景)
如果不想每次写完整路径,也可以给方法增加可选的分组参数,适配固定两层的表单结构:
public hasError = (controlName: string, errorName: string, groupName?: string) => { const baseGroup = groupName ? this.prozessPersonenzuordnungenForm.get(groupName) as FormGroup : this.prozessPersonenzuordnungenForm; return !!baseGroup?.controls[controlName]?.hasError(errorName); };
模板调用时单独传入分组名即可:
<mat-error *ngIf="hasError('nameC', 'required', 'person')">Bitte gebe eine Person an!</mat-error>
注意:不要在方法里省略空值判断,否则路径写错、动态表单控件未加载时会直接抛出JS错误导致页面异常。
内容的提问来源于stack exchange,提问作者ChopperChups
相关产品推荐
相关产品推荐

