0
我使用一些配置如何在HTML訪問formGroup傳遞給動態添加
創建動態表單我下面由託德·座右銘 Link
關注博客分量是我的形式
它包含嵌套FormGroups 所以我的配置包含一些節。部分包含一些fieldGroup和fieldGroup可以包含多個字段
這些字段是formControl,對此我傳遞[group](請參閱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);
}
我可以做form.controls.personal.controls.name得到表單組,其中個人和名字是我的表單組的名稱,但在渲染我DNT的時間有這些價值 –