'How to access dynamically created buttons in angular?

So, I am creating a quiz application where I have a scrollbar for questions and in that scrollbar I have buttons depending on the length of a question set. So I've created those buttons using *ngFor directive. Now what I want to do is whenever a user selects any option (mcq), the question buttons in the scrollbar should get highlighted in following way:

  1. If user selects any option, then change the question button color to Green
  2. If user skips the question, then change the question button color to Yellow

HTML Code for Question Scrollbar:

<div id="answer-buttons" class="ques-grid ">
            <button #navBarButton *ngFor="let item of items">{{item}}</button>
</div>

I'm have tried doing it by first accessing the buttons using ViewChild in ts file and then apply some logic, but it's not working, it is only changing the color of first button

@ViewChild('navBarButton',{ static: false }) navBarButton:ElementRef
//and in some function I've tried this logic
if(this.attemptedQuestionCount[this.currentQuestionIndex]==1){
  this.navBarButton.nativeElement.style.backgroundColor = "#228B22"
}
else{
  this.navBarButton.nativeElement.style.backgroundColor = "#FCF55F"
}

How can I achieve my objective?



Solution 1:[1]

Add button tag as follows:

<button *ngFor="let question of questions; let i=index"
        [style.background-color]="attemptedQuestionCount[i] === 1 ? '#228B22' : '#FCF55F'">{{question}}</button>

Solution 2:[2]

You can add the click handler directly to the button using

<button *ngFor="let item of items; let indexOfelement=index" 
      (click)="heyYouClicked(indexOfelement)">{{item}}</button>

And then in the component you place the handler

export class AppComponent {
  items = ["hello", "world"]

  heyYouClicked(index){
    console.log("you clicked " + index)
  }
}

Solution 3:[3]

You can try ngClass for simplicity.

<button #navBarButton *ngFor="let item of items" class="defualt_state" [ngClass]="{'new_state': (condition_here)}">{{item}}</button>

And in the stylesheet you can have the above class configured

.new_state { background-color: #228B22 !important }

And set the default color of the button this way

.default_state { background-color : #FCF55F}

So when the condition matches it will take the color specified in the new_state class or else will take the default color from default_state class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 samheist
Solution 2 Kokodoko
Solution 3 Marvin Delroy Aroza