Home > Mobile >  how to get value of selected button in angular
how to get value of selected button in angular

Time:11-17

I am creating a quiz application in angular.I am fetching data from api in which there are countries and their respective capitals.I have fetched them randomly and mapped them as questions and answers.Now i want to calculate the score.For this i am trying to get the value of selected button.I am doing this by document.getelementbyID("idx") ,but this returns me any random option not the option which i have selected.Can anybody help me with this

correct()  {
   var y= document.getElementById("idx")
  console.log(y)
    if(y==this.saveCap[this.userIndex]){
this.score=this.score 1;
console.log(true)
console.log(this.score)
// this.userIndex  ;
    }
 
 
  }
  checkoptions(){
   this.correct();
    this.userIndex  
    
  //  this.options.remove(this.x)
  this.arrayDel();
    this.arrayform();
    this.shuffle();
  }

HTML File

<h1>Quiz</h1>
<div *ngIf="saveCont && saveCap " >
    <form >
      <h1>What is the capital of{{saveCont[userIndex]}}</h1><br>
<li *ngFor="let cap of options"><button type="button"  (click)="checkoptions()" id="idx"  >{{cap}}</button></li>
     
    <button  (click)="res()">Submit</button>
     </form>
      
      </div>

CodePudding user response:

beacuse the id is added to both buttons it's not get you the tight button clicked. you need to pass the cap to the the click event like this:

<li *ngFor="let cap of options"><button type="button"  (click)="checkoptions(cap)" id="idx"  >{{cap}}</button></li>

and then inside checkoptions function get it

checkoptions(cap: string){
  // take the answer and check it and increase the score if it's correct
  this.correct(cap);
  this.userIndex  

   //  this.options.remove(this.x)
  this.arrayDel();
  this.arrayform();
  this.shuffle();
}
  • Related