如何在角度6中创建反应式问题选项表格(数据来自服务)

时间:2019-06-18 11:02:07

标签: angular6

我正在从服务中获取这些数据。

我想根据即将来临的数据创建一个反应性问题选项表格。在表单中,我需要创建问题和选项来选择。

ngOnInit() {
this.data.getQuestionList().subscribe(
      data => this.questions$ = data

);

从此函数中,我正在获取这些json数据

[{"question_id":"1","questions":"where do you live ?","options":[{"option_id":"1","options_name":"Village"},{"option_id":"2","options_name":"City"}]},{"question_id":"2","questions":"what is your qualification ?","options":[{"option_id":"3","options_name":"Graduate"},{"option_id":"4","options_name":"Masters"}]}]

我需要基于该json数据创建动态表单。假设我要创建一个表单,那么我将在ts文件中编写此内容。 ngOnInit(){

 this.registerForm = this.formBuilder.group({
        firstName: ['', Validators.required],
        lastName: ['', Validators.required],
        email: ['', [Validators.required, Validators.email]],
        password: ['', [Validators.required, Validators.minLength(6)]]
    });

} 但是对于动态名称,如何创建。假设问题1有3个选项,问题2有3个选项。选项字段名称应在问题ID上,例如问题1的option1 [],问题2的选项名称将是option2 []

1 个答案:

答案 0 :(得分:0)

尝试以下代码将起作用

您可以参考:https://stackblitz.com/edit/angular-wamyab-oujepa

component.ts

let questions = [{"question_id":"1","questions":"where do you live ?","options":[{"option_id":"1","options_name":"Village"},{"option_id":"2","options_name":"City"}]},{"question_id":"2","questions":"what is your qualification ?","options":[{"option_id":"3","options_name":"Graduate"},{"option_id":"4","options_name":"Masters"}]}]

component.html

<div >
  <ng-container *ngFor="let question of questions">
      <p>{{question.questions}}</p>
      <select>
        <option></option>
        <option *ngFor="let option of question.options">{{option.options_name}}</option>
      </select>

    </ng-container>
 </div>