我从 Angular 开始,我很难在表单中设置 FormArray。总之,我所做的是:
- 创建 2 个表单:主表单 (valForm) 和另一个动态创建的表单 (holidaysForm)。
- 将第二种形式的值复制到一个数组。
- 将 Array 的值加载到 FormArray 中。
遵循以下代码:
.ts
let group = {}
this.holidaysForm = new FormGroup(group);
this.valForm = fb.group({
dentistId: [null, Validators.required],
initialHour: [null, Validators.required],
endHour: [null, Validators.required],
numberOfHolidays: [null],
appointmentsInterval: [null, Validators.required],
year: [null, Validators.required],
workDays: this.buildDays(),
holidays: this.buildHolidays()
});
buildDays() {
const values = this.workDays.map(v => new FormControl(false));
return this.fb.array(values);
}
buildHolidays() {
if (typeof this.valForm !== 'undefined') {
let teste = Object.assign({}, this.holidaysForm.value);
this.holidays = new Array();
Object.values(teste).forEach((v) => {
this.holidays.push(v);
})
console.log(this.holidays);
const values = this.holidays.map((v)=> new FormControl(v));
return this.fb.array(values);
}
}
dynamicForm(val) {
if (val > 365) {
val = 365;
this.valForm.patchValue({
numberOfHolidays: 365
})
}
const val_plus_one = parseInt(val) + 1
let i: number = val_plus_one;
if (i < this.oldNumber) {
do {
this.holidaysForm.get('holiday' + i.toString()).setValue(null);
this.holidaysForm.removeControl('holiday' + i.toString());
i++
} while (i <= this.oldNumber)
}
const numbers = Array(val).fill(val, 0, 365).map((_, idx) => idx + 1)
numbers.forEach((num) => {
const fc = new FormControl('', FormValidations.Calendar(this.valForm.get('year').value));
this.holidaysForm.addControl('holiday' + num.toString(), fc)
})
this.numberOfHolidays = numbers;
this.oldNumber = val;
}
.html
<div class="col-md-4 mda-form-group">
<input class="mda-form-control" type="number" min="0" max="365"
formControlName="numberOfHolidays"
(change)="dynamicForm(valForm.get('numberOfHolidays').value)" />
<label>Total de Feriados</label>
</div>
<div [formGroup]="holidaysForm">
<div class="mda-form-group" *ngFor="let num of numberOfHolidays">
<input class="mda-form-control" type="date" formControlName="holiday{{num}}" />
<label>Feriado {{num}}</label>
<app-error-msg [control]="holidaysForm.get('holiday'+num)" label="Feriado">
</app-error-msg>
</div>
</div>
从理论上讲,代码运行良好且没有错误,问题是结果总是这样:
主表格
Valores:
{
"dentistId": null,
"initialHour": null,
"endHour": null,
"numberOfHolidays": 3,
"appointmentsInterval": null,
"year": null,
"workDays": [
false,
false,
false,
false,
false,
false,
false
],
"holidays": null
}
假期表格
{
"holiday1": "2020-01-01",
"holiday2": "2020-03-01",
"holiday3": "2020-02-01"
}
有谁知道我可能做错了什么?谢天谢地,