createForm() {
this.myForm = this.fb.group({
name: '',
lvl2: this.fb.array([
this.initLvl2(),
])
})
}
<form [formGroup]="myForm" novalidate>
<div formArrayName="lvl2">
<div *ngFor="let lvl2s of myForm.controls.lvl2.controls; let i=index let last=last">
<div class="panel-body" [formGroupName]="i">
<div *ngFor="let lvl3 of lvl2s.controls.lvl3.controls; let i=index let last=last" formArrayName="lvl3">
<div class="panel-body" [formGroupName]="i">
<div class="margin-20">
<button md-raised-button type="button" *ngIf="last" (click)="add()" style="cursor: default">Add Action</button>
</div>
</div>
</div>
</div>
</div>
initLvl2() {
return this.fb.group({
name: '',
lvl3: this.fb.array([
this.initLvl3()
])
})
}
initLvl3() {
return this.fb.group({
parameters: '',
wait_time: ''
})
}
add(){
const control = <FormArray>this.myForm.get('lvl2.lvl3')
control.push(this.initLvl3());
}
几个小时后,尝试了一切我都遇到了一些错误 无法读取属性'push'的null,如何处理?我对此感到厌倦,有几个问题,但大多没有好的答复
答案 0 :(得分:2)
由于lv2
是Array
,您必须将索引从模板传递给组件,以便获得与lv3
表单相关的组:
将您的function
更改为:
add(index: number): void {
const arr = this.myForm.get(`lvl2.${index}.lvl3`) as FormArray;
arr.push(this.initLvl3());
}