我正在尝试创建一个反应式表单,它将在页面上显示有关会议的详细信息,标签是动态的并从 API 返回。
这是返回数据的示例。
const meetings = [
{
id: 1,
date: '06/07/2018',
meetings: [
{
id: 1,
name: 'meeting 1',
times: [
{
id: 1,
name: '1PM'
},
{
id: 2,
name: '2PM'
}
]
},
{
id: 2,
name: 'meeting 2',
times: [
{
id: 3,
name: '3PM'
},
{
id: 4,
name: '4PM'
}
]
}
]
},
{
id: 2,
date: '07/07/2018',
meetings: [
{
id: 3,
name: 'meeting 3',
times: [
{
id: 5,
name: '8PM'
},
{
id: 6,
name: '9PM'
}
]
},
{
id: 4,
name: 'meeting 4',
times: [
{
id: 7,
name: '10PM'
},
{
id: 8,
name: '11PM'
}
]
}
]
}
];
这是我目前在我的 HTML 中的内容
<form [formGroup]="formf" novalidate (ngSubmit)="sub()">
<div *ngFor="let meeting of meetings">{{meeting.date}}
<div *ngFor="let details of meeting.meetings">{{details.name}}
<div formArrayName="meetingTime">
<div *ngFor="let timings of details.times; let i=index">
<div class="form-group">
<div formGroupName="{{i}}">
<label for="selected">{{timings.name}}</label>
<input formControlName="selected" class="form-control input-sm" type="checkbox" />
</div>
</div>
</div>
</div>
</div>
</div>
<input type="submit" [disabled]="!formf.valid" value="Save" />
</form>
在我的组件中,我正在创建一个初始化为的表单模型
initForm() {
this.formf = this.formBuilder.group({
meetingTime: new FormArray([])
});
}
当数据从 API 返回时,我尝试将其推送到 FormArray
setForm(meetingDate: MeetingDate[]) {
let meetingTimeArray = <FormArray>this.formf.controls['meetingTime'];
meetingDate.forEach(date => {
date.meetings.forEach(app => {
app.times.forEach(time => {
meetingTimeArray.push(this.formBuilder.group({
id: [time.id],
selected: false
}))
});
});
});
}
我在屏幕上打印了表单模型,当我单击复选框时,我可以看到它们仅更新前两个选定的值,我认为这是因为我已将 {{i}} 添加到 formGroupName 中,因此它们都映射到0, 1 个索引数组。