简体   繁体   中英

Loading dynamic form from JSON using angular 6

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM