此问题的一部分已在here之前得到了回答。
如果数组中的所有表单组都相同并且是动态生成的,则此方法效果很好。但是,例如,如果表单的第一步是完全不同的,那么在编写一些逻辑时就会产生麻烦。麻烦总是必须检查表单数组的索引,以确保您没有对错误的表单组类型应用逻辑。以我构建的形式,这会使代码变得很难阅读和维护。我正在寻找更清洁的解决方案。我知道您可以将单独的表单组附加到每个步骤。但是我找不到将表单数组和独立表单组附加到垫步进器组件的方法。
new-schedule.component.html:
<form [formGroup]="newScheduleForm" (ngSubmit)="onSubmit()">
<mat-horizontal-stepper [linear]="'false'" formArrayName="schedule">
<mat-step *ngFor="let a of newScheduleForm.get('schedule')?.controls; let stepGroup = index;" [stepControl]="stepGroup" label="{{getClassId(stepGroup)}}">
<ng-container *ngIf="stepGroup === 0" [formGroupName]="stepGroup">
// unique form code here
</ng-container>
<ng-container *ngIf="stepGroup !== 0" [formGroupName]="stepGroup">
// dynamica form code here
</ng-container>
<div class="data-form__control">
<button *ngIf="stepGroup !== 0" type="button" mat-button matStepperPrevious>Back</button>
<button *ngIf="stepGroup !== (newScheduleForm.get('schedule')?.length - 1)" type="button" mat-button matStepperNext>Next</button>
<button *ngIf="stepGroup === (newScheduleForm.get('schedule')?.length - 1)" mat-raised-button color="primary" type="submit">Submit</button>
</div>
</mat-step>
</mat-horizontal-stepper>
new-schedule.component.ts
// unique form group here
this.newScheduleForm = new FormGroup({
schedule: new FormArray([
new FormGroup({
location: new FormControl('', Validators.required),
}),
])
});
// dynamically generated form groups here
this.classList.map(item => {
(<FormArray>this.newScheduleForm.controls.schedule).push(new FormGroup({
classId: new FormControl(item.value, Validators.required),
dayGroups: new FormArray([])
}));
});
可以根据需要提供进一步的说明。