0

I am working on Angular 5 application and part of requirement is to create dynamic form from Web API Json data.

I have create multiple class of each input type i.e. text, radio, range, checkbox etc. I have tested all with hard-coded test metadata and is working. Now I need to create object of these classes dynamically in loop rather then hard-code as I have below define under test medtadata, each record in json is tag with questionType which tell which is input type

Test MetaData

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'},
        ],
      }),
  ];

example radio class

  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'] || [];
 }
}

Example of API;

point red arrow from where I know type, i.e in this case text so create object of textQuestion

enter image description here

Another Attempt

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
    })
   }
 }

in above code I am getting error block scoped variable used before its declaration when I try to push object into base class array

3
  • Do you have your an example of what your API will return? Commented Mar 12, 2018 at 16:52
  • I have update my question at bottom Commented Mar 12, 2018 at 17:05
  • so QuestionElement which is nested array got field TypeDefination that tells me which class to create object of current record in json array Commented Mar 12, 2018 at 17:07

1 Answer 1

1

Assming all your questions can be imported like this

import * as questions from "./question";

Then you can instantiate classes like this

let instance = new questions["className"];

So in your actual example, it could be

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);
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for detail, I try and hope this going to work
I did another attempt, update my question at bottom but getting error when i try to push class object to QuestionBase<any>[]; questions2.push(_textBox);
That's a different question that has nothing to do with the first one.. you wanted to create dynamically an instance of your question object based on a type, which is what my answer was for. What was the error when you tried that? In your updated post, you'll probably get an error because you push into `questions2``which is undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.