redd77
redd77

Reputation: 337

how to target a specific element generated by *ngFor?

I'm creating a quiz app with angular 6 as an image (question in this case) and 4 options ,and i need to change the color of the option that the user will click on, between 'red' and 'green' as it was right or false option . here' is my loop that generates the options :

 <div class="quiz_wrapper">
<div class="options">
  <ul>
    <li *ngFor="let Answer of displayedQuizAnswers" (click)="onChoseAnswer(Answer)" [ngStyle]="answerStyle">
      <a>{{Answer}}</a>
    </li>
  </ul>
</div>

when i change the "answerStyle" with the help of "onChoseAnswer(Answer)" it changes for all options . is there any approach that i can target a specific element style from the generated elements ?

Upvotes: 0

Views: 1265

Answers (2)

Eliseo
Eliseo

Reputation: 57929

redd, there're many ways to achive you want. The easer it's that your displayedQuizAnswers was an array of object. Imagine you has an array like

displayedQuizAnswers=[
   {question:'....',index:0,ok:false}
   {question:'....',index:1,ok:true}
   {question:'....',index:2,ok:false}
   {question:'....',index:3,ok:false}
]

And a variable

response:number=-1

you can write, e.g.

<ul>
    <li *ngFor="let answer of displayedQuizAnswers;let i=index" 
        [style.background-color]="response==i?answer.ok?'green':'red':'inherit'">
      <a (click)="response==-1 && i=response">{{answer.question}}</a>
    </li>
  </ul>

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222542

If you want to have it for a specific element, you need to add that property to the object Answer individually.

 <li *ngFor="let Answer of displayedQuizAnswers" (click)="onChoseAnswer(Answer)" [ngStyle]="{{answer.Style}}">
      <a>{{Answer}}</a>
 </li>

Upvotes: 1

Related Questions