简体   繁体   English

使用 angular 6 从 JSON 加载动态表单

[英]Loading dynamic form from JSON using angular 6

I am creating angular 6 dynamic forms by using link, https://angular.io/guide/dynamic-form我正在使用链接创建 angular 6 动态表单, https://angular.io/guide/dynamic-form

Here i have given following in question.service.ts,在这里,我在 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,我想从 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,其中 element 在控制台中给出的值是,

{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] ..但是,虽然我收到的错误是undefined .. 当我控制台问题也显示为[undefined] ..

How to pass the dynamic json values inside the form object like textbox?如何在表单对象(如文本框)中传递动态 json 值? 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.我创建了一个示例应用程序,它根据您的动态 json 生成带有验证的表单。 Please refer stackblitz example : reactive form dynamic validation请参考 stackblitz 示例: 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.如您所见,上面的代码中,我生成了具有 value 属性的 FormGroup,因为其他属性与表单无关。

Now I have applied loop of dynamicJSON array object in the HTML and binds the form.现在我已经在 HTML 中应用了 dynamicJSON 数组对象的循环并绑定了表单。

Here is the HTML code :这是 HTML 代码:

<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.您没有在问题数组中推送 TextboxQustion 对象。 I have created sample example on stackblitz , please check.我已经在stackblitz上创建了示例示例,请检查。

Here is the ts code.这是ts代码。

let newArray = this.dynamicJSON;

    let questions: any = [    ]

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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