Search code examples
javascripthtmlangulartypescriptmean-stack

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

  • You can check for attemptedQuestionCount and change background color like this

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