Angular响应式表单动态多控件数据绑定问题求助
解决Angular Reactive Form休息时段数据绑定问题
问题原因
你在HTML模板中处理FormArray的方式错误:每个休息时段是一个FormGroup,但你直接给输入框绑定了[formControlName]="i",这无法正确关联到FormGroup内部的from和to控件,导致数据绑定失效。
修复方案
1. 修改HTML模板的休息时段渲染逻辑
需要先为循环中的每个FormGroup绑定索引,再在内部用formControlName关联对应的字段:
<div formArrayName="breaks" class="row mt-3"> <!-- 遍历breaks数组中的每个FormGroup,绑定当前索引 --> <div *ngFor="let breakGroup of breaks.controls; let i=index;" [formGroupName]="i" class="row mb-2"> <div class="col"> <div class="form-group"> <label>Break({{i+1}}) From</label> <input type="time" class="form-control" formControlName="from"> </div> </div> <div class="col"> <div class="form-group"> <label>Break({{i+1}}) To</label> <input type="time" class="form-control" formControlName="to"> </div> </div> <div class="col"> <div class="form-group mt-2"> <button type="button" (click)="removeBreak(i)" class="btn btn-danger mt-4">Remove</button> </div> </div> </div> </div>
2. (可选)优化TypeScript代码可读性
抽离创建休息时段FormGroup的逻辑,便于后续维护:
export class AddAppointmentFormComponent implements OnInit{ addAppointmentForm!: FormGroup constructor(private _fb:FormBuilder, private _wfmService:WFMService) {} ngOnInit(): void { this.addAppointmentForm = this._fb.group({ typeOfDayId :['',Validators.required], appointMentDate: ['', Validators.required], from: ['', Validators.required], to: ['', Validators.required], breaks: this._fb.array([]) }) } get breaks(){ return this.addAppointmentForm.get('breaks') as FormArray; } // 单独创建休息时段的FormGroup private createBreakGroup(): FormGroup { return this._fb.group({ from: ['', Validators.required], to: ['', Validators.required], }) } addBreak(){ this.breaks.push(this.createBreakGroup()); } removeBreak(i:any){ this.breaks.removeAt(i); } }
修复后效果
此时{{ addAppointmentForm.value | json }}会输出你期望的格式:
{ "typeOfDayId": "", "appointMentDate": "", "from": "", "to": "", "breaks": [ { "from": "10:00", "to": "10:30" }, { "from": "14:00", "to": "14:30" } ] }
内容的提问来源于stack exchange,提问作者Hameed Hassam
相关产品推荐
相关产品推荐

