从嵌套类设计嵌套反应形式 [英] Designing nested reactive forms from nested classes
问题描述
我有以下课程:
class License {
name:string;
.. lots of other fields.
nameAttributes:NameAttributes[];
}
class nameAttributes:NameAttributes{
index:number;
attribute:string;
}
我知道我可以像这样创建表单,但它要求我手动创建每个字段(控件),并且每次许可证类更改时,我都必须使用新字段更新类和此 formGroup.
I know I can created the form like this, but it requires that I manually create each field(control) and every time the licences class changes, I have to update the class and this formGroup with the new fields.
this.licenseForm = formBuilder.group({
name:['name value'],
otherFields:['their values'],
nameAttributes: this.formBuilder.array([
this.formBuilder.group({
index:[1],
attribute:["attr1"]
}),
this.formBuilder.group({
index:[2],
attribute:["attr2"]
})
])
});
如果我可以将许可证类传递给 formBuilder,它会自动创建必要的 FormGroups 并根据它们的名称使它们可用,我更愿意,因此以下将创建两个组,一个许可证"组和一个嵌套的"nameAttributes"组,包含许可证和 nameAttributes 的所有关联控件.
I would prefer if I could just pass the license class into formBuilder and it would create the necessary FormGroups automatically and make them available based on their name, so the following would create two groups, a "license" group and a nested "nameAttributes" group with all of the associated controls for license and nameAttributes.
this.licenseForm = formBuilder.group({
license:formBuilder.group(license)
});
我是不是遗漏了什么,或者如果没有一些严肃的类内省代码,这是不可能的?
Am I missing something or is this just not possible without some serious class introspection code?
推荐答案
如果你的对象有数据,当然可以
If your object has data, of course you can do it
看看这个 stackblitz
你有一个类似的功能
createForm(data:any):FormGroup
{
const group=new FormGroup({});
for (let key in data)
{
if (Array.isArray(data[key])) //if is an array
{ //first create the formArray
group.addControl(key,new FormArray([this.createForm(data[key][0])]))
for (let i=1;i<data[key].length;i++) //after add the rest of the elements
(group.get(key) as FormArray).push(this.createForm(data[key][i]))
}
else
{
if (typeof(data[key])=="object") //if is an object we add a formGroup
group.addControl(key,this.createForm(data[key]))
else //add a simple control
group.addControl(key,new FormControl(data[key]))
}
}
return group
}
并称之为
this.form=this.createForm(this.obj)
这篇关于从嵌套类设计嵌套反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!