javascript - 在 HTML 中绘制表单组
问题描述
我正在尝试根据来自服务器的数据绘制表单的 HTML 嵌套部分,没有预定义嵌套部分的数量,如下所示
{
"structure": [
{
"id": "1",
"title": "Section 1",
"structure": [
{
"id": "1_1",
"title": "section 1_1",
"structure": [
{
"id": "1_1_1",
"title": "section 1_1_1"
}
]
},
{
"id": "1_2",
"title": "section 1_2",
"structure": [
{
"id": "1_2_1",
"title": "section 1_2_1"
}
]
}
]
},
{
"id": "2",
"title": "section 2",
"structure": [
{
"id": "2_1",
"title": "section 2_1",
"structure": [
{
"id": "2_1_1",
"title": "section 2_1_1"
}
]
},
{
"id": "2_2",
"title": "section 2_2",
"structure": [
{
"id": "2_2_1",
"title": "section 2_2_1"
}
]
}
]
}
]
}
HTML
<form [formGroup]="subjectForm">
<div formArrayName="structure">
<ng-container
*ngTemplateOutlet="
sectionDetails;
context: {
sectionIndex: sectionIndex,
sectionForm: subjectForm.controls.structure.controls[sectionIndex]
}
"
></ng-container>
<ng-template
#sectionDetails
let-tempSectionIndex="sectionIndex"
let-tempSectionForm="sectionForm"
>
<div [formGroupName]="tempSectionIndex">
<input
type="text"
nbInput
formControlName="title"
status="info"
placeholder="Section titless"
/>
<div formArrayName="structure">
<ng-container
*ngFor="
let form of tempSectionForm.controls.structure.controls;
let i = index
"
>
<ng-container
*ngTemplateOutlet="
sectionDetails;
context: {
sectionIndex: i,
sectionForm: tempSectionForm.controls.structure.controls[i]
}
"
></ng-container>
</ng-container>
</div>
</div>
</ng-template>
</div>
</form>
formgroup 在 component.ts 中创建得很好,但我在 HTML 中绘制 formgroup 时遇到问题,问题是子部分未按预期顺序绘制,例如第 1_1 节出现在第 1_1_1 节的位置......等等
组件.ts
ngOnInit() {
this.subjectService.createSubjectForm(this, this.subject);
}
formService.js
createSubjectForm(scope, subject) {
scope.subjectForm = this.fb.group({
'path': [[]],
});
if (subject.subjectFormatSubjects)
this.createSectionForm(scope.subjectForm.controls, subject.subjectFormatSubjects.data)
}
createSectionForm(formPath, sections) {
if (!formPath['structure'])
formPath['structure'] = this.fb.array([]);
sections.forEach((section) => {
(<FormArray>formPath['structure'].controls).push(this.fb.group({
'title': [section.title, Validators.required]
}));
const sectionIndex = formPath['structure'].controls.length - 1;
formPath['structure'].controls[sectionIndex].controls['path'] = this.fb.control([...formPath.path.value, sectionIndex]);
if (section.subjectFormatSubjects) {
this.createSectionForm(formPath['structure'].controls[sectionIndex].controls, section.subjectFormatSubjects.data);
}
});
}
解决方案
推荐阅读
- java - lambda 表达式相对于方法变量的优势是什么?
- javascript - 在 javascript 中保存类对象(循环引用)-> JSON.stringify-error
- c# - 循环中的 WebClient 工作一次,然后超时
- javascript - 与 Date.now() 相比,来自 firebase 的解码令牌的到期日期
- go - 转储非主包的 Go 程序集
- c++ - MSVC 是否存在等效于 GCC 的 used 属性?
- python - ValueError:长度必须匹配才能进行比较
- java - SSL期间在openshift上运行的Kafka出错
- perl - 循环遍历perl中的列的问题
- reactjs - 为选定页面导出带有道具的导航栏