我试图从服务中加载嵌套的对象数据,然后将所有这些数据放入窗体中,并与FormBuilder和FormArray分组。我能够使用服务数据的值创建表单,但是遇到一个问题,即表单的最后一个嵌套对象无法获取其值,我尝试了多个具有1个或多个记录的示例数据,但总会发生表格中最后一个嵌套的记录没有值,但是当我手动更改缺少的表格值的离子输入时,该表格能够获取更改后的值,然后出现在正确的formArray中。以下是与该表单创建相关的我的.ts文件和html。
ngOnInit() {
this.getSchemeDetail();
this.form = this._FB.group({
'scheme_id': ['', Validators.required],
'components': this._FB.array([]),
});
}
getSchemeDetail(){
this.mschemeService.getMScheme(this.mschemeID).subscribe(
(data) => {
this.component = data;
for(var i = 0; i < this.component.length; i++){
var obj = this.component[i];
this.category = obj.category
console.log(this.category)
}
this.loadForm(this.component)
}
)
}
loadForm(component : M_Component[]){
for (let line = 0; line < component.length; line++){
const compFormArray = this.form.get('components') as FormArray;
compFormArray.push(this.comps);
compFormArray.patchValue(component)
for (var i in component[line].category){
const cateFormArray = compFormArray.at(line).get('category') as FormArray
cateFormArray.push(this.cates);
cateFormArray.patchValue([component[line].category])
console.log(i)
}
}
}
get comps(): FormGroup{
return this._FB.group({
'COMPONENT_ID': [''],
'TITLE': ['', Validators.required],
'DESC': [''],
'category': this._FB.array([])
})
}
get cates(): FormGroup{
return this._FB.group({
'CRITERIA': [''],
'POINTS': ['']
})
}
<ion-card *ngFor="let mcomp of component; let comps of form['controls'].components['controls']; let i = index" formGroupName="{{i}}">
...
<tbody *ngFor="let mcate of mcomp.category; let cates of comps['controls'].category['controls']; let j = index" formGroupName="{{j}}">
以下是具有不同记录数的form.value的结果,基本上服务数据能够与表单值链接,但是嵌套“ category” formArray(条件和点)的最后一条记录无法将服务数据转换为表单值。请随时纠正我,谢谢!
//Example of Form Value with 2 records
{components: [
{'COMPONENT_ID': 17,
'TITLE': 'Understanding in skills',
'DESC': 'abc',
'SUB_POINT': 20,
'category': [
{'CRITERIA': 'Only minimal understanding shown of subject matter.',
'POINTS': '0 - 4'},
{'CRITERIA': 'Good understanding.',
'POINTS': '5 - 10'}
],
{'COMPONENT_ID': 18,
'TITLE': 'Test2',
'DESC': 'abcd',
'SUB_POINT': 20,
'category': [
{'CRITERIA': '',
'POINTS': ''},
{'CRITERIA': '',
'POINTS': ''}
],
}
}
//Example of Form Value with 1 records
{components: [
{'COMPONENT_ID': 16,
'TITLE': 'Test1',
'DESC': 'abcd',
'SUB_POINT': 20,
'category': [
{'CRITERIA': '',
'POINTS': ''},
{'CRITERIA': '',
'POINTS': ''}
],
}
}