4

I am creating angular 6 dynamic forms by using link, https://angular.io/guide/dynamic-form

Here i have given following in question.service.ts,

 getQuestions() {

    let questions: DynamicBase<any>[] = [

      new TextboxQuestion({
        key: 'firstName',
        label: 'First name',
        type: 'text',
        value: '',
        required: true,
        order: 1
      }),

      new TextboxQuestion({
        key: 'emailAddress',
        label: 'Email',
        type: 'email',
        order: 2
      }),

      new DropdownQuestion({
        key: 'brave',
        label: 'Bravery Rating',
        options: [
          {key: 'solid',  value: 'Solid'},
          {key: 'great',  value: 'Great'},
          {key: 'good',   value: 'Good'},
          {key: 'unproven', value: 'Unproven'}
        ],
        order: 4
      }),
    ];

    return questions.sort((a, b) => a.order - b.order);
}

Here instead of

  new TextboxQuestion({
    key: 'firstName',
    label: 'First name',
    type: 'text',
    value: '',
    required: true,
    order: 1
  }),

I would like to load the data from the JSON,

"dynamicJSON": [
    {
        "key": "role_name",
        "label": "Role Name",
        "type": "text",
        "value": "",
        "required": true,
        "order": 1
    },
    {
        "key": "last_ame",
        "label": "Last Name",
        "type": "text",
        "value": "",
        "required": true,
        "order": 2
    }
]

For which i have used the following,

    let newArray = dynamicJSON;

    let questions: DynamicBase<any>[] = [    

    newArray.forEach(element => { 
        new TextboxQuestion(element)
    });

    ];

    return questions.sort((a, b) => a.order - b.order);

Where element gives the value in console as,

{key: "role_name", label: "Role Name", type: "text", value: "", required: true, …}

But whereas i am getting the error as key of undefined.. When i console questions also displays as [undefined]..

How to pass the dynamic json values inside the form object like textbox? Kindly help me to get out of it, stucked for a long..

1
  • Can you do this to push your array into the newarray and then do other operations on it json.Results.forEach(element => { newArray.push(element.Id); }); Commented Oct 31, 2018 at 8:51

2 Answers 2

4

I have created an sample application, which is generating the form with validation based on your dynamic json. Please refer stackblitz example : reactive form dynamic validation

I have implemented the shortest(less code) approach to generate the dynamic form.

Here is the component code :

ngOnInit(){
    this.sortDynamicJson();
    this.questionFormGroup = this.formBuilder.group({
      questions:this.formBuilder.array([])
    })
    this.generateForm()
  }

  generateForm(){
    this.dynamicJSON.forEach(t=>{
      let questions =<FormArray> this.questionFormGroup.controls["questions"]; 
     questions.push(this.formBuilder.group({
       value:[t.value,[t.required ? Validators.required:null]]
     }))
    })
  }

As you see the above code, I have generated the FormGroup with value property, because other properties are not related to the form.

Now I have applied loop of dynamicJSON array object in the HTML and binds the form.

Here is the HTML code :

<form >
  <div [formGroup]="questionFormGroup.controls.questions.controls[i]" *ngFor="let row of dynamicJSON; let i = index;">
<div class="form-group">
    <label>{{row.label}}</label>
    <input type="text" formControlName="value" class="form-control"  />
</div>
</div>
<<button [disabled]="!questionFormGroup.valid" class="btn btn-primary">Submit</button>

Please let me know if you have any question.

Sign up to request clarification or add additional context in comments.

Comments

2

You are not pushing TextboxQustion object in questions array. I have created sample example on stackblitz, please check.

Here is the ts code.

let newArray = this.dynamicJSON;

    let questions: any = [    ]

    newArray.forEach(element => { 
        questions.push(element)
    });


    questions.sort((a, b) => a.order - b.order);

8 Comments

Thanks for your help.. Can you kindly generate at-least one textbox in your example you have provided. Because using this i am getting only label and required field message.. If you generate one textbox then it would be much more helpful..
Ok, I will update you after some time, is there any other dynamic validation needed in the form or just required?
Ajay, As i am new in angular and dynamic form, kindly help me to get out of it.. From my understanding i have developed the above like in question.. The requirement is i need to create a sample of textbox, radio button, selectbox using dynamic form and that too values needs to be from that dynamic JSON, as of now i have this requirement.. If any needed i will update you.. I request you to generate textbox, radio, selectbox alone from the JSON using dynamic form.. Kindly help me please..
I have shared two optimum solution for dynamic JSON validation, please let me know if you have any question in one of the solution which is best for your application.
Ajay, thanks for your valuable time for it but those new two solution is not what i expected.. The old one which i have posted and the first answer(this comment's answer) modification alone what i expected.. I also should not add any third party plugins in my project.. I know dynamic form is part of a reactive form but i need to use everything in angular dynamic form alone.. With this answer can you modify the same dynamic form and give the result of a textbox, checkbox, radio button alone in the view?
|

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.