我正在开发Angular 5应用程序,部分要求是从Web API Json数据创建动态表单。
我创建了每个输入类型的多个类,即文本,广播,范围,复选框等。我已经使用硬编码的测试元数据测试了所有类型并且正在工作。现在我需要在循环中动态创建这些类的对象而不是硬编码,因为我在下面定义了测试medtadata,json中的每个记录都是带有questionType的标记,它告诉哪个是输入类型
getQuestions() {
let questions: QuestionBase<any>[] = [
new DropdownQuestion({
key: 'brave',
label: 'How you Rate New steel X technology for industrial construction ',
options: [
{key: 'solid', value: 'Solid'},
{key: 'great', value: 'Great'},
{key: 'good', value: 'Good'},
{key: 'unproven', value: 'Unproven'}
],
order: 1
}),
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 5
}),
new DropdownQuestion({
key: 'ice-cream',
label: 'which ice-cream you prefer?',
options: [
{key: 'Vanilla', value: 'Vanilla'},
{key: 'banana', value: 'banana'},
{key: 'apple', value: 'apple'},
],
order: 3
}),
new TextboxQuestion({
key: 'weekend',
label: 'What you doing this weekend?',
order: 4
}),
new RadioButtonQuestion ({
key: 'eating-ice-cream',
label: 'What ice-crea you like to eat?',
order: 6,
options: [
{name:'ice-cream', key: 'Vanilla', value: 'Vanilla'},
{name:'ice-cream', key: 'banana', value: 'banana'},
{name:'ice-cream', key: 'apple', value: 'apple'},
],
}),
];
import { QuestionBase } from './question-base';
export class RadioButtonQuestion extends QuestionBase<string> {
controlType = 'radio';
options: {name:string, key: string, value: string}[] = [];
constructor(options: {} = {}) {
super(options);
this.options = options['options'] || [];
}
}
指向我知道类型的红色箭头,即在这种情况下文本创建textQuestion的对象
let questions2: QuestionBase<any>[];
for(var key in questionsList)
{
let questionElementType = questionsList[key].questionElement.questionElementType[0].typeDefination;
if(questionElementType=="textbox")
{
var _textBox =
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 5
});
console.log("_textBox",_textBox);
questions2.push(_textBox);
}
else if(questionElementType=="dropdown")
{
new DropdownQuestion({
key: 'brave',
label: 'How you Rate New steel X technology for industrial construction ',
options: [
{key: 'solid', value: 'Solid'},
{key: 'great', value: 'Great'},
{key: 'good', value: 'Good'},
{key: 'unproven', value: 'Unproven'}
],
order: 1
})
}
}
在上面的代码中,当我尝试将对象推入基类数组时,我得到了在声明之前使用的错误块作用域变量
答案 0 :(得分:1)
确认您可以像这样导入所有问题
import * as questions from "./question";
然后你可以实例化像这样的类
let instance = new questions["className"];
所以在你的实际例子中,它可能是
let questionType = "textbox";//the type you showed on your screenshot
let classType = `${questionType.charAt(0).toUpperCase()}${questionType .slice(1)}Question`;
let questionInstance new questions[classType](options);