如何访问嵌套数组以显示Angular表单中levels的<input>字段?
解决方案
1. 修正TypeScript中levels的获取逻辑
原代码中levels getter直接从learningGoals这个FormArray获取levels是错误的——learningGoals是数组,每个元素才是包含levels的FormGroup,必须针对单个learningGoal的索引来获取对应levels数组。
修改后的TS代码:
rubricForm: FormGroup; constructor(private fb: FormBuilder) { this.rubricForm = this.fb.group({ name: ["", Validators.required], learningGoals: this.fb.array([ this.initLearningGoal() ]) }); } initLevel() { return this.fb.group({ name: "", criteras: this.fb.array([]) // 补全目标JSON结构中的criteras数组 }); } initLearningGoal() { return this.fb.group({ description: "", levels: this.fb.array([ this.initLevel() // 默认初始化一个level ]) }); } learningGoals(): FormArray { return this.rubricForm.get("learningGoals") as FormArray; } // 根据learningGoal索引获取对应levels数组 getLearningGoalLevels(index: number): FormArray { return (this.learningGoals().at(index) as FormGroup).get('levels') as FormArray; }
2. 修正模板表单路径并添加操作按钮
模板中遍历levels时,必须使用当前learningGoal的索引调用getLearningGoalLevels方法,同时添加添加/删除level、添加learningGoal的按钮:
<form [formGroup]="rubricForm"> <ng-template matStepLabel>Naam & Niveaus</ng-template> <mat-form-field> <input matInput placeholder="Naam" formControlName="name"> </mat-form-field> <div formArrayName="learningGoals"> <div *ngFor="let learningGoal of learningGoals().controls; let i = index" [formGroupName]="i"> <!-- Learning Goal描述输入框 --> <mat-form-field> <input matInput placeholder="Leerdoel beschrijving" formControlName="description"> </mat-form-field> <div formArrayName="levels"> <h4>Niveaus voor leerdoel {{i+1}}</h4> <!-- 遍历当前learningGoal的levels --> <div *ngFor="let level of getLearningGoalLevels(i).controls; let j = index" [formGroupName]="j"> <mat-form-field> <input matInput placeholder="Niveau naam" formControlName="name"> </mat-form-field> <button mat-button (click)="removeLevel(i, j)">Verwijder niveau</button> </div> <button mat-button (click)="addLevel(i)">Voeg niveau toe</button> </div> </div> </div> <button mat-button (click)="addLearningGoal()">Voeg leerdoel toe</button> </form>
3. 补充TS中的操作方法
添加以下方法实现表单控件的增删:
// 添加新的learningGoal addLearningGoal() { this.learningGoals().push(this.initLearningGoal()); } // 给指定learningGoal添加新level addLevel(learningGoalIndex: number) { this.getLearningGoalLevels(learningGoalIndex).push(this.initLevel()); } // 删除指定learningGoal中的指定level removeLevel(learningGoalIndex: number, levelIndex: number) { this.getLearningGoalLevels(learningGoalIndex).removeAt(levelIndex); }
错误原因说明
之前出现的ERROR Error: Cannot find control with path: 'learningGoals -> levels',是因为levels属于每个learningGoal表单组的子数组,而非直接属于learningGoals数组的控件。原模板中未绑定到当前遍历的learningGoal的levels数组,导致表单路径匹配失败。
内容的提问来源于stack exchange,提问作者Robin R
相关产品推荐
相关产品推荐

