angular 2如何使用可重复的代码并正确显示json数据

时间:2016-04-18 13:06:09

标签: angular

我是角2的菜鸟,我真的需要制作一些可用的代码。

有没有办法制作一个更短的可用版本

answer1 = false;
answer2 = false;
answer3= false;

onClick1(){
   this.answer1 = true; 
   this.answer2 = false; 
   this.answer3 = false; 
 };

 onClick2(){
   this.answer1 = false; 
   this.answer2 = true; 
   this.answer3 = false; 
 };

 onClick3(){
   this.answer1 = false; 
   this.answer2 = false; 
   this.answer3 = true; 
 };

以及任何人都知道如何我倾向于显示这些信息,因为我知道这是不对的。我带来了这个json代码

[{
        "id": 1,
        "question":"What do you think of the new platform?",
        "Answers":{ 
        "answer1": "It's awesome",
        "answer2": "It's no better than the old version",
        "answer3": "It's confusing!"}



    }];

我只能使用* ngIf显示它,即使它只是一个信息?

<p (click)="onClick1()" [class.active]="answer1" *ngFor="#question of questions">{{question.Answers.answer1}}</p>
<p (click)="onClick2()"[class.active]="answer2" *ngFor="#question of questions">{{question.Answers.answer2}}</p>
<p (click)="onClick3()"[class.active]="answer3" *ngFor="#question of questions">{{question.Answers.answer3}}</p>

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你可以尝试类似的东西:

answers = {
  answer1: false,
  answer2: false,
  answer3: false,
};

onClick(answerNumber) {
  Object.keys(this.answers).forEach((key) => this.answers[key] = false);
  this.answers[answerNumber] = true; 
}

并在模板中以这种方式使用它:

<template ngFor #answer [ngForOf]="answers | keyValues">
  <p (click)="onClick(answer.key)" 
        [class.active]="answers[answer.key]"
        *ngFor="#question of questions">
    {{question.Answers[answer.key]}}
  </p>
</template>

请参阅此plunkr:https://plnkr.co/edit/6DenBCOfVnRRVy1rqPmN?p=preview

此问题中描述了键/值管道: