Reputation: 2115
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?
Upvotes: 1
Views: 54
Reputation: 202156
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:
Upvotes: 1