首页 > 解决方案 > 根据数据在角度内动态生成单选按钮

问题描述

我有一个场景,我试图显示单选按钮,说一个问题有两个答案:1)蔬菜 2)非蔬菜,所以当我选择蔬菜时,它还有三个选项和第三个选项“蔬菜和水果的混合物”里面还有进一步的问题等等。

以下是我正在使用的参考 json

"choices": {
      "1": {
        "text": "Vegeterian",
        "questions": {
          "1": { 
            "choices": {
              "1": { "text": "Only Veggies" },
              "2": { "text": "Only Fruits" },
              "3": {
                "text": "Mixture of Vegetable and Fruits",
                "questions": {
                  "1": {
                    "type_name": "selectOne",
                    "choices": {
                      "1": {
                        "text": "Yes.. No animal product",
                        "questions": {
                          "1": {
                            "type_name": "selectOneOrMore",
                            "choices": {
                              "1": {
                                "text": "You are a nice human being"
                              },
                              "2": {
                                "text": "You are a good human being"
                              }
                            }
                          }
                        }
                      },
                      "2": {
                        "text": "No meat. but other animal product"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "2": { "text": "Non-Vegeterian"}
    }

在有角的前面,我刚刚显示了外部两个选项,如果有更多问题和选项,我如何动态选择单选按钮添加更多问题

    <ng-container *ngFor="let consult of choices | keyvalue; let j = index; trackBy: trackByFn;">
              <td>
                   <input  type="radio" name="radio" id="radio-{{j}}" />
                   <label class="sr-text" for="radio-{{j}}">{{consult.value.text}}</label>
              </td>
   </ng-container>

标签: angular

解决方案


您可以创建一个呈现“问题”的组件和一个呈现“选择”的组件。如果选择本身就是一个问题,则递归地使用组件。

显示这种方法的一些代码(未经测试,您必须使其适应您自己的数据结构):

@Component({
  template: `
  ...
  <div ngFor="choice in question.choices">
    <appChoice [choice]="choice"
  </div>
  `
})
class QuestionComponent {
  @Input() question;
  ...
}

@Component({
  template: `
  <div ngIf="isQuestion; else notQuestion">
    <appQuestion [choices]="choice.question">
  </div>
  <ng-template #notQuestion>
    ...
  </ng-template>
  `
})
class ChoiceComponent {
  @Input() choice;
  get isQuestion() { return !!this.choice.question; }
  ...
}

推荐阅读