Angular 11 中如何实现嵌套 Form Array 功能?
Angular 11 嵌套FormArray实现方案
TS代码修改
首先修正原有逻辑的隐患:你之前直接复用同一个group实例推送进FormArray,会导致所有表单项共享同一份数据,修改任意一项都会同步影响其他项,所以先将固定实例改为工厂函数,再新增address相关的操作方法:
spinner: boolean = false; new_created: boolean = true; create_question_form: FormGroup; // 改为工厂函数,每次调用生成全新的FormGroup实例 getNewQuestionGroup(): FormGroup { return new FormGroup({ name: new FormControl(''), address: new FormArray([]) // 新增address FormArray }); } // 新增:获取指定问题下的address FormArray getAddressByQuestionIndex(index: number): FormArray { return this.question.at(index).get('address') as FormArray; } // 新增:给指定问题添加新的地址项 addAddress(questionIndex: number) { const addressGroup = new FormGroup({ // 可按需求自定义地址相关字段,示例新增detail字段 detail: new FormControl('') }); this.getAddressByQuestionIndex(questionIndex).push(addressGroup); } constructor(private route: ActivatedRoute, private fb: FormBuilder) {} validation() { this.create_question_form = this.fb.group({ question: new FormArray([this.getNewQuestionGroup()]), }); } get question() { return this.create_question_form.get('question') as FormArray; } add_question() { // 调用工厂函数生成新的问题组,避免引用复用 this.question.push(this.getNewQuestionGroup()); } create_question() { const data = this.create_question_form.getRawValue(); console.log(data); } ngOnInit(): void { this.validation(); }
HTML模板修改
在原有name输入框的同级位置,按层级嵌套绑定address FormArray即可,不要跳级访问:
<form [formGroup]="create_question_form" (ngSubmit)="create_question()" > <ng-container formArrayName="question"> <div *ngFor="let _ of question.controls; index as questionIndex"> <ng-container [formGroupName]="questionIndex"> <div class="col-12 col-md-4 mt-5"> <span class="p-float-label w-100"> <input type="text" id="inputtext{{questionIndex}}" class="form-control" formControlName="name" pInputText /> <label for="inputtext{{questionIndex}}">Name</label> </span> </div> <!-- 嵌套address FormArray 开始 --> <ng-container formArrayName="address"> <div *ngFor="let __ of getAddressByQuestionIndex(questionIndex).controls; index as addrIndex"> <ng-container [formGroupName]="addrIndex"> <div class="col-12 col-md-4 mt-3 ms-5"> <span class="p-float-label w-100"> <input type="text" id="address{{questionIndex}}{{addrIndex}}" class="form-control" formControlName="detail" pInputText /> <label for="address{{questionIndex}}{{addrIndex}}">地址详情</label> </span> </div> </ng-container> </div> <!-- 新增地址按钮,绑定当前问题的索引 --> <button type="button" class="btn btn-secondary mt-2 ms-5" (click)="addAddress(questionIndex)"> 新增地址 </button> </ng-container> <!-- 嵌套address FormArray 结束 --> </ng-container> </div> </ng-container> <button type="button" class="btn btn-primary mt-3 me-2" (click)="add_question()">新增问题</button> <button type="submit" class="btn btn-success mt-3">Create</button> </form>
注意事项
- 所有表单输入框的id要保证唯一,示例中拼接了索引避免重复
- 每次新增表单组都调用工厂函数生成新实例,避免多个表单项数据绑定冲突
- FormArray嵌套访问时必须严格遵循层级:外层FormArray -> 对应索引的FormGroup -> 内层FormArray -> 对应索引的地址FormGroup
内容的提问来源于stack exchange,提问作者Mohd Sabban
相关产品推荐
相关产品推荐

