我正在使用一些配置创建一个动态表单
我正在关注 Todd Motto Link的博客
以下是我的表格
它包含嵌套的 FormGroups,因此我的配置包含许多部分。Section 包含多个 fieldGroup 和 fieldGroup 可以包含多个字段
这些字段是formControl,我将[组](参见ng-container)传递给我想传递formGroup的这个组。现在我只传递一个字符串
<form
class="dynamic-form"
[formGroup]="form"
(submit)="handleSubmit($event)">
<md-tab-group>
<div *ngFor="let section of config.sections" >
<md-tab label={{section.title}} formGroupName={{section.title}}>
<div *ngFor="let fieldGroup of section.fieldGroups" >
<div class="card-block card mb-3" formGroupName={{fieldGroup.name}}>
<ng-container *ngFor="let field of fieldGroup.fields;" dynamicField [config]="field" [group]="fieldGroup.name">
</ng-container>
</div>
</div>
</md-tab>
</div>
</md-tab-group>
<button>Submit</button>
</form>
这是我的 component.ts
ngOnInit(): void {
this.form = this.createForm();
console.log(this.form);
}
createForm(){
const group = this.fb.group({});
this.config.sections.forEach(section=>group.addControl(section.title,this.addFieldGroups(section)));
return group;
}
addFieldGroups(section): FormGroup{
const group = this.fb.group({});
section.fieldGroups.forEach(fieldGroup=>group.addControl(fieldGroup.name,this.addFieldGroup(fieldGroup)));
return group;
}
addFieldGroup(fieldGroup): FormGroup{
const group = this.fb.group({});
fieldGroup.fields.forEach(field=>group.addControl(field.name, this.createControl(field)));
return group;
}
createControl(config) {
const { disabled, validation, value } = config;
return this.fb.control({ disabled, value }, validation);
}