我有一个动态构造行的表,如下所示
<form [formGroup]='employeeForm'>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">contact details</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let details of employeeDetails'>
<th formControlName='name' scope="row">{{details.name}}</th>
<td formControlName='employeeName'>{{details.contactDetails}}</td>
</tr>
</tbody>
</table>
</form>
现在,如何将动态创建的控件附加到窗体?我试过了
employeeForm: FormGroup
constructor(private formbuilder: FormBuilder) { }
ngOnInit() {
this.employeeForm = this.formbuilder.array([])
}
,但它给我的错误是,formGroup不能包含formArray
如何使用reactive form方法将formArray添加到formGroup中?
发布于 2019-03-18 02:44:54
FormGroup
和FormArray
都是包含FormGroups、FormArrays和/或FormControls的容器。
employeeForm: FormGroup;
nameArray: FormArray;
ngOnInit(){
this.nameArray = new FormArray([
new FormControl('name1'),
new FormControl('name2')
]);
this.employeeForm = new FormGroup({
employeeNameArray: this.nameArray
});
}
<tr *ngFor="let employeeName of nameArray.controls; let i=index">
<td>Name: <input type="text" [formControlName]="i"></td>
</tr>
如果希望每个employee有多个表单元素(例如,一个用于姓名,另一个用于地址),则可能需要再嵌套一层,其中表单数组的直接子元素为FormGroups,然后每个子元素都包含一个名称FormControl和一个地址FormControl。
https://stackoverflow.com/questions/55204896
复制相似问题