我正在尝试创建一个反应式表单,该表单将在有关会议的页面上显示详细信息,标签是动态的,并且是从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索引数组。
答案 0 :(得分:0)
我已经做到了这一点,不确定这是否是最有效的方法,但是它有效!
我没有将索引添加到* ngFor上,而是将其添加到打字稿中,在该打字稿中我将控件推送到表单模型。
setForm(meetingDate: MeetingDate[]) {
let index = 0;
let meetingsArray = <FormArray>this.formf.controls['meetingTime'];
meetingDate.forEach(date => {
date.meetings.forEach(app => {
app.times.forEach(time => {
meetingsArray.push(this.formBuilder.group({
id: [time.id],
selected: false
}))
time.index = index;
index++;
});
});
});
this.meetings = meetingDate;
}