So I am a real beginner and I am obviously missing something. I am creating a quiz style app and I have a list with a radio group in that loops through an array using ngfor to present the answers
The list is a list of answers and what I am trying to do is change the color of the item when they click on it, i.e. green for correct and red for incorrect.
It works but the problem is that it changes the whole list (i.e. every item, not just the item I have clicked on)
Here is my code
html
<button ion-item *ngFor="let answer of question.answers; let i = index ;" [ngStyle]="{'background-color': answerColor}" wrap-text>
<ion-label class="my-label" text-wrap>{{answer.answer}}</ion-label>
<ion-radio (click)="selectAnswer(answer, question)" [checked]="answer.selected" [disabled]="hasAnswered"></ion-radio>
</button>
ts
if(answer.correct){
this.score++;
this.answerColor = '#025c25'; //correct Green Color
}
else{
this.answerColor = '#AB2020'; //Wrong Red Color
}
this.slides.lockSwipes(false);
So there are no errors it just makes the whole list green or red depending on the answer whereas I just want the item I am clicking on to change color.
I have read loads of stuff about ng-class and lots of links but cant quite get my head around it. Apologies if this is a really dumb question or I have approached it all wrong
This is happening because you only have a single
answerColor
variable that all of your answers are using, instead of having oneanswerColor
peranswer
.If you can add a color variable to your
answer
objects and change your code to useanswer.answerColor
instead ofthis.answerColor
, then the colors should work as you expect they would. In the following snippet, I have updated your logic to useanswer.answerColor
.Finally, if your
answer
object is declared to be a specific type (instead ofany
), then you may need to update the type definition.