Jayden
Jayden

Reputation: 283

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>

Upvotes: 2

Views: 14525

Answers (3)

Shafeeq Mohammed
Shafeeq Mohammed

Reputation: 1298

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

Upvotes: 0

user11208420
user11208420

Reputation:

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.

Upvotes: 0

jitender
jitender

Reputation: 10429

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

Upvotes: 6

Related Questions