'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 1:[1]

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

Solution 2:[2]

First of all change button type to type tag. Then you can assign id and value to the tag.

other solution is you can add change or click events to button and to click methods you can send some values to function in your javascript.

Solution 3:[3]

its only an example for working with Radio Button

.HTML

<div class="form-check-inline">
    <label class="form-check-label">
    <input type="radio" class="form-check-input"  checked="!checked" name="radio"  [(ngModel)]="radio" [value]="true">active
  </label>
</div>
<div class="form-check-inline">
  <label class="form-check-label">
    <input type="radio" class="form-check-input" 
                      checked="!checked"name="radio1"  [(ngModel)]="radio1" [value]="true">Deactive
  </label>
</div>
<button (click)="print( radio,radio1)"> shaa</button>

.ts

  radio=false;
radio1=false;
  print(){
  console.log(this.radio,this.radio1)
  this.radio = false;
  this.radio1 = false;
}

Stackbliz example

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 jitender
Solution 2
Solution 3 Shafeeq Mohammed