【问题标题】:angular 2 how do i use repeatable code and display json data properly角度 2 我如何使用可重复的代码并正确显示 json 数据
【发布时间】:2016-08-10 05:52:01
【问题描述】:

我是 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>

有人有什么想法吗?

【问题讨论】:

    标签: angular


    【解决方案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。

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

    【讨论】:

    • 非常感谢!你是一个 angular2 向导!我不知道它是如何工作的,我很高兴它做到了:)
    • 不客气 ;-) 中心点是要有一个包含可能答案的键的对象...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多