Angular嵌套表单FormArray内字段如何通过ngIf正确显示校验错误
完全可以实现seniority、resourceNotes、skill这类嵌套字段的校验错误提示,核心逻辑和主表单字段校验一致,只要正确按层级访问到嵌套表单控件即可。
1. 组件类补充便捷访问方法
在你的现有ts代码中添加以下getter和工具方法,简化嵌套FormArray的访问:
// 获取顶层resourceDTOS FormArray get resourceDTOS(): FormArray { return this.myForm.get('resourceDTOS') as FormArray; } // 根据索引获取对应资源项下的skillDTOS FormArray getSkillDTOS(resourceIndex: number): FormArray { return this.resourceDTOS.at(resourceIndex).get('skillDTOS') as FormArray; }
2. 模板嵌套表单校验写法
按照表单的层级结构,逐层声明formArrayName、formGroupName,再对应写校验逻辑即可,示例代码如下:
<!-- 顶层resourceDTOS遍历 --> <div formArrayName="resourceDTOS"> <div *ngFor="let resourceGroup of resourceDTOS.controls; let resourceIdx = index" [formGroupName]="resourceIdx"> <!-- seniority字段校验 --> <input formControlName="seniority" type="text" placeholder="资历"> <small *ngIf="resourceGroup.get('seniority').invalid && resourceGroup.get('seniority').touched" class="text-danger">请填写资历信息</small> <!-- resourceNotes字段校验 --> <textarea formControlName="resourceNotes" placeholder="资源备注"></textarea> <small *ngIf="resourceGroup.get('resourceNotes').invalid && resourceGroup.get('resourceNotes').touched" class="text-danger">请填写资源备注</small> <!-- 嵌套skillDTOS遍历 --> <div formArrayName="skillDTOS"> <div *ngFor="let skillGroup of getSkillDTOS(resourceIdx).controls; let skillIdx = index" [formGroupName]="skillIdx"> <input formControlName="skill" type="text" placeholder="技能"> <small *ngIf="skillGroup.get('skill').invalid && skillGroup.get('skill').touched" class="text-danger">请填写技能信息</small> </div> </div> <button type="button" (click)="addNewResourceSkill(getSkillDTOS(resourceIdx))">新增技能</button> </div> </div> <button type="button" (click)="addNewResourceDTOS()">新增资源</button>
注意事项
- 嵌套层级的
formArrayName、formGroupName不能漏写,必须和ts中的表单结构完全对应,否则会找不到控件 - 你当前初始化resourceDTOS子项时,默认的第一个skill没有加必填校验,如果需要第一个skill也触发校验,初始化时把
skill: ''修改为this.fb.control('', Validators.required)即可 - 如果要在提交时统一触发表单所有字段的校验,只需要调用
this.myForm.markAllAsTouched()即可,嵌套字段也会同步触发touched状态,错误提示会统一展示
内容的提问来源于stack exchange,提问作者john555
相关产品推荐
相关产品推荐

