【发布时间】:2019-12-28 17:41:47
【问题描述】:
我想生成动态表单。预期输出:
{"laboratories":[{"colArr":[{"col":"11"},{"col":"22"},{"col":"33"}]},{"colArr":[{"col":"5"},{"col":"423"}]}]}
laboratories 是我的主键,它计算行数。 colArr 是每一行的键,在 colArr 里面我有动态列没有添加 formcontrolname col
所以按照上面的 JSON:我有两行(第一行有 3 列,第二行有两列)
我尝试过的代码:
home.html
<form [formGroup]="laboratoryForm">
<div formArrayName="laboratories">
<ion-row *ngFor="let obj of laboratoryForm.controls.laboratories.controls; let i=index" style="background-color: red;">
<div [formGroupName]="i">
<div formArrayName="colArr">
<ion-col *ngFor="let item of obj.controls.colArr.controls; let j=index" style="background-color: green;">
<span [formGroupName]="j">
<ion-input placeholder="Enter Input" formControlName="col"></ion-input>
</span>
</ion-col>
</div>
</div>
</ion-row>
</div>
</form>
home.ts
public laboratoryForm: FormGroup;
noOfRows = 0;
constructor(public navCtrl: NavController, private _fb: FormBuilder) {
this.laboratoryForm = this._fb.group({
laboratories: this._fb.array([
this._fb.group({
colArr: this._fb.array([
this._fb.group({
col: ['']
})
])
})
]),
});
this.AddItemData();
}
AddItemData() {
//Add new data to Form
const control = <FormArray>this.laboratoryForm.controls['laboratories'];
this.noOfRows++;
control.push(this._fb.group({
colArr: [this.addColData(3)]
})
);
}
addColData(noOfcolumns) {
const docs = <FormArray>this.laboratoryForm.controls['laboratories'];
for (let row = 0; row < this.noOfRows; row++) {
var grp = <FormGroup>(docs.controls[row])
const colArrReceived = <FormArray>grp.controls['colArr'];
for (let indx = 0; indx < noOfcolumns; indx++) {
var colGrp = <FormGroup>(colArrReceived.controls[indx]);
colGrp.controls['col'].patchValue('');
}
}
}
我怎样才能找到我的错误?
【问题讨论】:
-
请附上任何错误信息以帮助调试
-
好的,我做了一个快速的stackblitz ionic-blank-6yjgws.stackblitz.io
-
你可以从错误信息中看到你正在尝试使用不存在的控件,即 colArrReceived.controls[index] 其中父 ColArrReceived 的长度只有 1
标签: angular forms ionic-framework ionic3 angular4-forms