Search code examples
angularradio-button

How to handle multiple radio buttons - Angular


Here I have list of yes or no questions and provide radio buttons for the user to choose the answer for each individually - also providing two buttons for "All Yes" and "All No".

Individually selecting is fine but I don't know how to bind either the "All Yes" or "All No" buttons and collect the values of each question.

<div *ngFor="let question of questionsList; let i=index; ">
  <label>
    {{question.id}} 
    <input type="radio" [name]="i + 1">
    <span>Yes</span>
    <input type="radio" [name]="i + 1">
    <span>No</span><br>
  </label>
</div>

<div style="text-align: center">
  <button type="button">All Yes</button>
  <button type="button">All No</button> 
  <button type="button">Submit</button>
  <button type="button">Clear</button>  
</div>

Solution

  • Set [value] attribute for radio button and than use ngModel for two way binding and add some property like isSelected to your model to set true/false for all something like

    <div *ngFor="let question of questionsList; let i=index; ">
        <label>
                {{question.id}} 
            <input type="radio" [value]="true" [(ngModel)]="question.isSelected"  [name]='i+1'>
                <span>Yes</span>
            <input type="radio" [value]="false" [(ngModel)]="question.isSelected"  [name]='i+1' >
                <span>No</span><br>
        </label>
    </div>
    

    In your component

    selectAll(){
        this.questionsList.forEach(i=>{
          i.isSelected=true;
        })
      }
    
      unSelectAll(){
        this.questionsList.forEach(i=>{
          i.isSelected=false;
        })
      }
    

    Demo