我想创建一个动态表单,在运行时我无法创建,我选择父选项。每个孩子都有不同的输入,只需要一个,所以我不能在父组件中创建表单,我必须在选定的孩子上进行。
我正在尝试在父级中创建表单并将其传递给子级,如下一个示例,但在子级中我没有正确接收表单。
我做错了什么?
Parent.html
<form [formGroup]="myForm">
<div *ngFor="field of fields; let i as index">
<select [value]="value">
<option value="child1">type1</option>
<option value="child2">type2</option>
<option value="child3">type3</option>
</select>
<div [ngSwitch]="value">
<child-one *ngSwitchCase="'child1'" [index]="i" [myForm]="myForm"></child-one>
<child-two *ngSwitchCase="'child2'" [index]="i" [index]="i" [myForm]="myForm"></child-two>
<child-three *ngSwitchCase="'child3'" [index]="i" [index]="i" [myForm]="myForm"></child-three>
</div>
</div>
</form>
Parent.ts
~~~~~~~~~~~
this.myForm = fb.group({
fields[0]: fb.group({}),
fields[1]: fb.group({}),
fields[n]: fb.group({}),
});
~~~~~~~~~~~
child1.html
<form [formGroup]="i">
<input type="checkbox" [formName]="child1foo1"></input>
<input type="checkbox" [formName]="child1foo2"></input>
</form>
child1.ts
~~~~~~~~~~~
@Input() myForm: FormGroup;
@Input() index: number;
this.myForm.fields(index).group(
.... the inputs of this child...);
~~~~~~~~~~~
child2.html
<form [formGroup]="i">
<input type="text" [formName]="child2foo1"></input>
<input type="text" [formName]="child2foo2"></input>
<input type="number" [formName]="child2foo3"></input>
</form>
child2.ts
~~~~~~~~~~~
@Input() myForm: FormGroup;
@Input() index: number;
this.myForm.fields(index).group(
.... the inputs of this child...);
~~~~~~~~~~~
child3.html
<form [formGroup]="i">
<input type="number" [formName]="child3foo1">></input>
<input type="number" [formName]="child3foo2">></input>
</form>
child3.ts
~~~~~~~~~~~
@Input() myForm: FormGroup;
@Input() index: number;
this.myForm.fields(index).group(
.... the inputs of this child...);
~~~~~~~~~~~