提问人:Francisco 提问时间:6/7/2022 最后编辑:Francisco 更新时间:6/7/2022 访问量:106
在html中访问FormBuilder数据
Accessing FormBuilder data in the html
问:
我初始化了一个FormBuilder,然后把数据放进去,如下代码:
generateTable(dataJobs: any): void {
this.formBuilder = this.fb.group({
jobs: this.fb.array([
this.fb.group({
name: this.fb.control(null),
operations: this.fb.array([])
})
])
})
this.jobs.removeAt(0)
for (let i = 0; i < dataJobs.length; i++) {
this.jobs.push(this.fb.group({ name: dataJobs[i].name, operations: [dataJobs[i].operations] }))
}
}
我有这个方法来访问工作
get jobs() {
return this.formBuilder.get('jobs') as FormArray;
}
formBuilder 的值是这样的:
{
"jobs": [
{
"name": "job0",
"operations": [
"(M0,3)",
"(M1,2)"
]
},
{
"name": "job1",
"operations": [
"(M1,3)",
"(M1,2)"
]
}
]
}
我尝试在html中执行以下代码,但没有得到任何东西
<table>
<form [formGroup]="formBuilder">
<thead>
<tr class="fw-bolder fs-6 text-gray-800">
<th>#</th>
<th>2</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr formArrayName="jobs"
*ngFor="let jobs of formBuilder.get('jobs')['controls']; let i=index">
<td formArrayName="operations"
*ngFor="let operations of formBuilder.get('jobs')['controls'][i].get('operations')['controls']; let ind =index">
{{operations}} {{ind}}
</td>
<td>Tiger Nixon</td>
<td>Tiger Nixon</td>
</tr>
</tbody>
</form>
</table>
如何使用formBuilder制作表格?
答:
1赞
Chellappan வ
6/7/2022
#1
不允许在表格内添加表单,它被视为无效的 html。将表单移到表格外
<form [formGroup]="formBuilder">
<table>
<thead>
<tr class="fw-bolder fs-6 text-gray-800">
<th>#</th>
<th>2</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr
formArrayName="jobs"
*ngFor="let jobs of formBuilder.get('jobs')['controls']; let i = index"
>
<ng-container [formGroupName]="i">
<td
formArrayName="operations"
*ngFor="
let operation of formBuilder
.get('jobs')
['controls'][i].get('operations')['controls'];
let ind = index
"
>
{{ operation.value }} {{ ind }}
</td>
</ng-container>
<td>Tiger Nixon</td>
<td>Tiger Nixon</td>
</tr>
</tbody>
</table>
</form>
然后,您需要为操作键创建控件数组,而不是直接分配数组值
for (let i = 0; i < dataJobs.length; i++) {
this.jobs.push(this.fb.group({ name: dataJobs[i].name, operations:
this.fb.array( dataJobs[i].operations.map(operation=>this.fb.control(operation))) }))
}
评论
0赞
Francisco
6/7/2022
对不起,无聊了,我可以在操作中输入吗?@Chellappan வ
1赞
Chellappan வ
6/7/2022
不客气!。您的意思是在 HTML 中添加输入?
0赞
Francisco
6/7/2022
是的,每个操作都是表内的一个输入,更改后也会更改formBuilder的值,可能吗?
1赞
Chellappan வ
6/7/2022
是的,可能,我现在已经更新了 stackblitz 检查
上一个:将字符串列表转换为整数列表
评论
but I didn't get anything
你期待什么? 它不会为您创建 HTML,它只是从指定的配置初始化您的数据表单。FormBuilder