我从服务器接收一个json数组,如何用angular 2 formarray映射这个数组

时间:2016-12-21 11:31:57

标签: json angular

我收到的json数组看起来像这样

questions = [
{
q_name="question 1",
op_1="op 1",
op_2="op 2",
answer=1
},
{
q_name="question 2",
op_1="op 1",
op_2="op 2",
answer=2
}
];

我希望以带有单选按钮的形式显示此数据以选择选项 如何实现这一点,我是角色2的新手

1 个答案:

答案 0 :(得分:0)

您必须在组件中更新问题集合对象,如下所示。

//Define private variable
questions: any;

//List of questions
this.questions = [
{
    "q_name":"question 1",
    "op_1":"op 1",
    "op_2":"op 2",
    "answer":"op 1"
},
{
    "q_name":"question 2",
    "op_1":"op 3",
    "op_2":"op 4",
    "answer":"op 4"
}
];

现在,在 HTML 渲染单选按钮如下:

<div *ngFor="let question of questions;let i=index">
<div>
    Question : {{question.q_name}}
</div>    
<div>
    <input type="radio" [(ngModel)]="question.answer" name="{{i}}" value="question.op_1">{{question.op_1}}<br />
    <input type="radio" [(ngModel)]="question.answer" name="{{i}}" value="question.op_2">{{question.op_2}}<br />
</div>