1

i am a noob to angular 2 and i really need to make some reuable code.

is there a way to make a shorter reuable version of this

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; 
 };

aswell as that does anyone know how i am surpossed to be displaying this information as i know this isnt right. i am bringing in this json code

[{
        "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!"}



    }];

and i can only seem to display it by using *ngIf even though it is only one peice of information?

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

anyone have any ideas?

1 Answer 1

1

You could try something like that:

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

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

and use it this way in the template:

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

See this plunkr: https://plnkr.co/edit/6DenBCOfVnRRVy1rqPmN?p=preview.

The key / value pipe is described in this question:

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! you are a angular2 Wizard! I have no idea how that works i'm just glad it does :)
You're welcome ;-) The central point is to have an object containing the keys for possible answers...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.