如何访问HTML中的formGroup以传递给动态添加的组件 [英] How to access a formGroup in HTML to pass to a component added dynamically
问题描述
我正在使用某些配置创建动态表单
I am creating a dynamic form using some configuration
我正在关注Todd Motto的博客链接
i am following a blog by Todd Motto Link
以下是我的表格
它包含嵌套的FormGroups所以我的配置包含许多部分.部分包含多个fieldGroup,fieldGroup可以包含多个字段
It contains nested FormGroups so my config contain a number of section. Section contains a number of fieldGroup and fieldGroup can contain a number of fields
这些字段是formControl,我要传递给它[group](请参阅ng-container)我想通过formGroup到这个组.现在我只传递一个字符串
these fields are formControl, to this i am passing [group] (see ng-container) to this group i want to pass formGroup. Right now i am passing just a string
<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>
这是我的组件.
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);
}
推荐答案
好吧,我没有得到任何答案,所以这就是我所做的
Well i didnt get any answer so this is what i have done
在ng-container中的HTML中
in HTML in ng-container
[group]="getFormGroup(section.title,fieldGroup.name)"`
所以我正在调用传递字符串的函数
so i am calling a function passing the strings
这就是我检索formGroup的方式
and this is how i am retrieving formGroup
getFormGroup(sectionName,fieldGroupName){
var section = this.myForm.controls[sectionName] as FormGroup;
var fieldGroup =section.controls[fieldGroupName];
return fieldGroup;
}
这篇关于如何访问HTML中的formGroup以传递给动态添加的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!