我想在表头(之前-星期一,星期二..)中添加复选框,并使用角度反应形式在数据网格中动态添加行。
Week1, Week2..
值通过
weeks = ['Week1','Week2','Week3','Week4']
类似地,列标题也循环了另一天。
需要使用FormArray
反应式表单来实现列标题和所有行中的复选框的某种方式。
有人可以帮忙吗?
答案 0 :(得分:1)
这是做我想做的事情的可能方法:
1-生成FormGroup
days = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
weeks = ['Week1', 'Week2', 'Week3'];
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.formGroup = this.fb.group({
weeks: this.fb.array(this.initFormDatas())
});
console.log(this.formGroup);
}
initFormDatas() {
const groups = [];
this.weeks.forEach((week) => {
groups.push(this.fb.array(this.initDaysFormControls(week)));
});
return groups;
}
initDaysFormControls(week) {
const controls = [];
this.days.forEach((days) => {
controls.push(new FormControl());
});
return controls;
}
您可以轻松适应的简化HTML: onWeekSelected是一个简单功能,可让您选择或取消选择列的每个复选框
<form [formGroup]="formGroup" (ngSubmit)="submitForm()">
<table>
<thead>
<th *ngFor="let day of days">
<input type="checkbox" (change)="onWeekSelected($event)" /> {{ day }}
</th>
</thead>
<tbody formArrayName="weeks">
<tr *ngFor="let week of weeks; let weekIndex=index">
<td> {{ week }} </td>
<ng-container [formArrayName]="weekIndex">
<td *ngFor="let day of days; let dayIndex=index">
<input type="checkbox" [formControlName]="dayIndex" />
</td>
</ng-container>
</tr>
</tbody>
</table>
<button type="submit"> Submit </button>
</form>
提交时的结果:
submitForm() {
console.log(JSON.stringify(this.formGroup.value));
}