我的目标是将外部json数据修补到包含FieldArrayType的表单。
说我有以下形式的字段配置:
fields: FormlyFieldConfig[] = [
{
key: 'cars',
type: 'repeat',
fieldArray: {
fieldGroupClassName: 'row',
templateOptions: {
btnText: 'Add',
},
fieldGroup: [
{
className: 'col-sm-4',
type: 'input',
key: 'type',
templateOptions: {
label: 'Type:'
},
},
{
type: 'input',
key: 'name',
className: 'col-sm-3',
templateOptions: {
label: 'Name:'
},
},
],
},
},
];
后来我想修补一些数据到这个重复类型:
patchData() {
let data = {
"cars":[
{"type":"Type1","name":"Name1"},
{"type":"Type2","name":"Name2"}]
};
// Failure: Only the first car value is patched, the second car is not patched
// (unless) 'Add' is clicked first, which is not intended.
this.form.patchValue(data);
}
问题是在表单的初始加载时,重复部分中只存在一个项目。因此,如果我将数据修补到包含两个或多个字段数组项的表单,则只应用第一个项并将其存储在模型中。
有没有办法在修补数据之前以编程方式将项添加到FieldArray,以便模型接收数据?
注意:数据的长度可能会有所不同。
请参阅以下stackblitz作为示例:https://stackblitz.com/edit/angular-vfykhx
constructor(
private fb: FormBuilder
)
patchData() {
this.form=this.fb.group({
cars:this.fb.array([])
});
let data = {
"cars":[
{"type":"Type1","name":"Name1"},
{"type":"Type2","name":"Name2"}]
};
const fa = <FormArray>this.form.controls['cars'];
data.cars.forEach((each)=>{
let tFormGroup:FormGroup=this.fb.group({
type:[each.type],
name:[each.name]
});
tFormGroup.patchValue(each);
fa.push(tFormGroup);
})
}
<form [formGroup]="form">
<div formArrayName="cars">
<div *ngFor="let car of form['controls'].cars;let i=index;" [formGroupName]="i">
<input ype="text" formControlName="type">
<input ype="text" formControlName="name">
</div>
</div>
</form>