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..

Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
  • 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); });` – Vaibhav Oct 31 '18 at 08:51

2 Answers2

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.

Ajay Ojha
  • 380
  • 1
  • 3
  • 9
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);
Ajay Ojha
  • 380
  • 1
  • 3
  • 9
  • 1
    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.. – Maniraj Murugan Oct 31 '18 at 09:31
  • 1
    Ok, I will update you after some time, is there any other dynamic validation needed in the form or just required? – Ajay Ojha Oct 31 '18 at 09:38
  • 1
    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.. – Maniraj Murugan Oct 31 '18 at 09:41
  • 1
    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 Ojha Nov 01 '18 at 01:46
  • 1
    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? – Maniraj Murugan Nov 01 '18 at 04:49
  • I had given ```questions.push(new TextboxQuestion(element));``` instead of ```questions.push(element)``` in this soulution , its generating textbox but i don't know whether it is a correct way.. – Maniraj Murugan Nov 01 '18 at 04:53
  • You don’t need to create textbox class object. Directly generate the form based on server data. For showing different control based on data then I would suggest try to use ngswitch or ngif. Ngswitch is recommended, please refer angular dynamic form example for ngswitch. – Ajay Ojha Nov 01 '18 at 05:40
  • Thanks for your help, i will accept your answer.. Can you help me out in https://stackoverflow.com/questions/53097348/building-angular-dynamic-form-in-nested which also my recent question.. As you know very well about dynamic form hope you can help me for it.. – Maniraj Murugan Nov 01 '18 at 08:22