我正在努力实现从JSON
数据动态创建Angular表单。
我已经使用Angular站点上的example作为参考,我使用了模拟数据服务,但是在使用实际数据时我正在与实现进行斗争。
Angular模拟数据方法如下所示(使用静态数据构建form
和formFields
):
getFields() {
let fields: FormBase<any>[] = [
new DropdownField({
key: 'brave',
label: 'Bravery Rating',
options: [
{ key: 'solid', value: 'Solid' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'unproven', value: 'Unproven' }
],
order: 3
}),
new TextboxField({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}),
new TextboxField({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
})
];
return fields.sort((a, b) => a.order - b.order);
}
}
我真实array
的数据objects
看起来像这样(只需一个object
来说明):
[
{
Name:"Pallet Quantity",
Type:"Integer",
Required: false,
Units:[
{
Name:"Kilograms"
},
{
Name:"Tonnes"
}
]
}
]
以下是我尝试使用我的数据实施Angular FormBase<any>[]
,new DropdownField
和new TextboxField
:
createFields(dataArray) {
let order = 0;
let newArray = [];
let tempArray = [];
let modifiedArray = [];
for (let i = 0; i < dataArray.length; i++) {
let controlType = null;
switch (dataArray[i].Type) {
case 'Integer':
controlType = 'number';
break;
default: controlType = 'text';
break;
};
if (dataArray[i].Units.length > 0) {
modifiedArray = [];
tempArray = dataArray[i].Units;
tempArray.forEach(unit => {
modifiedArray.push({
key: unit.Name,
value: unit.Name
});
});
}
newArray.push({
key: dataArray[i].Name,
placeholder: dataArray[i].Name,
order: order++,
required: dataArray[i].Required,
controlType: controlType,
options: modifiedArray
});
}
return this.createFormAndFields(newArray);
}
createFormAndFields(newArray) {
let fields: FormBase<any>[] = [];
let dropDownArray;
let textBoxArray;
for (let i = 0; i < newArray.length; i++) {
if (newArray[i].options.length > 0) {
dropDownArray = [
new DropdownField(newArray[i])
]
}
if (newArray[i].options.length === 0) {
textBoxArray = [
new TextboxField(newArray[i]),
]
}
}
dropDownArray.push(...textBoxArray);
fields.push(dropDownArray);
return fields.sort((a, b) => a.order - b.order);
}
我没有收到错误,但没有创建任何表单或字段。我究竟做错了什么?感谢您的建议和帮助。