我正在尝试将从webapi接收的对象修补为角度反应形式。该表单还具有表单数组。但是,尽管有超过 3 条或更多条记录,但只有 2 条记录被修补到反应式表单的表单数组中。
我有两个实体 noseries 和 noseriesList,其中 noseries 有零个或多个 noseriesLists。因此,从webapi获得noseries后,我想将noseries的属性和导航列表"noseriesLists"修补为反应形式。其余属性正在正确修补,但只有 2 条导航列表"noseriesLists"的记录被修补到嵌套在反应式表单中的 formArray。
//initialization of form
this.noseriesForm = this.fb.group({
id: [null],
description: ['', Validators.required],
code: [ '', Validators.compose([Validators.maxLength(10), Validators.required])],
noSeriesList: this.fb.array([
this.initLine(), this.initLine()
])
});
//patching the object received from service to form
this.route.params.subscribe(routeParam => {
if (routeParam.id) {
this.noseriesService.get(routeParam.id)
.subscribe((data: NoSeries) => {
this.isCreateMode = false;
this.noseries = data;
this.noseriesForm.patchValue(this.noseries);
console.log(this.noseries, 'data from api');
console.log(this.noseriesForm.value,'formvalue');
});
}
});
//initialise formArray
initLine(): FormGroup {
return this.fb.group({
id: [null],
startingNoSeries: ['', Validators.required],
endingNoSeries: '',
lastUsedSeries: '',
effectiveDate: [null],
endingDate: [null],
noSeriesId: [null]
});
}
记录从服务接收的数据显示 3 条无系列列表记录,而记录 formvalue 仅显示 2 条无系列列表记录。
首次初始化表单数组时,将添加两个空控件。 这就是为什么当您将值修补到 FormGroup 时,只有这两个空控件会被填充。 在修补值之前,您应该用要修补的控件数填充表单数组。
//patching the object received from service to form
this.route.params.subscribe(routeParam => {
if (routeParam.id) {
this.noseriesService.get(routeParam.id).subscribe((data: NoSeries) => {
this.isCreateMode = false;
this.noseries = data;
const nsList = this.noseriesForm.get("noSeriesList") as FormArray;
nsList.clear();
this.noseries.forEach(_ => nsList.push(this.initLine()));
this.noseriesForm.patchValue(this.noseries);
console.log(this.noseries, 'data from api');
console.log(this.noseriesForm.value,'formvalue');
});
}
});