angular - 根据数据在角度内动态生成单选按钮
问题描述
我有一个场景,我试图显示单选按钮,说一个问题有两个答案: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>
解决方案
您可以创建一个呈现“问题”的组件和一个呈现“选择”的组件。如果选择本身就是一个问题,则递归地使用组件。
显示这种方法的一些代码(未经测试,您必须使其适应您自己的数据结构):
@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; }
...
}
推荐阅读
- proxy - 无法使用量角器在 Chrome 浏览器中打开 UI
- angularjs - 哪种数据库和聊天库适合使用 Ionic 框架的基于聊天的应用程序
- angular - 在Angular6中的另一个FormArray中显示FormArray
- java - Windows 中的 Docker:无法为 Linux amd64 加载本机库“libnative-platform.so”
- android - 具有双向绑定的自定义组件
- latency - aerospike 与 aws 的不良延迟
- javascript - javascript中的元素分组
- android - Android Google 文字转语音语言支持
- javascript - 如何从选定的输入字段中获取值(不使用 id)
- android - 前台服务不起作用 i LG K10 2017 android 7.0 设备