Doflamingo19
Doflamingo19

Reputation: 1629

How get checked value from radio button angular

I need to get value from radio button in angular. Suppose to have this html code:

 <label class="radio-inline">
   <input class="form-check-input" type="radio" [(ngModel)]="dog" name="gob" value="i" [checked]="true" (change)="onItemChange(item)"/>Dog
 </label>
 <label class="radio-inline"> 
   <input class="form-check-input" type="radio" [(ngModel)]="cat" name="cat" value="p"  (change)="onItemChange(item)"/>Cat
 </label>

In my ts page I need to get the value of radio button like

dog.value

My purpose is:

  1. Set default cheched to first radio button
  2. Get the value when I click on radio button

Anyone can help me?

Upvotes: 27

Views: 159993

Answers (3)

Christian Paul Gastardo
Christian Paul Gastardo

Reputation: 1261

In your code, in order to group the radio buttons, they should have the same input for name attribute.

To solve your problem, you can use *ngFor to loop through the radio inputs,

HTML:

    <div *ngFor="let opt of options; let i=index">
      <label class="radio-inline">
        <input type="radio" class="form-check-input" [value]="opt.value" [name]="opt.name" [checked]="i == 0"
        (change)="onRadioChange(opt)"/>
      </label>
    </div>

TS:

interface Option {
 name: string;
 value: string;
}

options: Option[] = [
 {
   name: "pet",
   value: "dog"
 },
 {
   name: "pet",
   value: "cat"
 }
]

onRadioChange(opt: Option) {
 console.log(`Value is: ${opt.value}`)
}

Defining a radio group

Upvotes: 0

Hossein Ganjyar
Hossein Ganjyar

Reputation: 823

One of the easiest way is do like this:

html:

<input
type="radio"
id="a"
name="sample"
value="pure"
(change)="onChange($event)"
checked /> 
<label for="a">A</label> 

<input
type="radio"
id="b"
name="sample"
value="b"
(change)="onChange($event)" />
<label for="b">B</label>

ts:

onChange(e) {
   this.type= e.target.value;
}

Upvotes: 5

Sunil
Sunil

Reputation: 11243

You can bind the data of radio button. Just add the value for radio button and change in the ngModel

html

<input class="form-check-input" type="radio" value="dog" 
[(ngModel)]="dog.value" name="gob" value="i" [checked]="true" 
(change)="onItemChange($event.target.value)"/>

ts

onItemChange(value){
   console.log(" Value is : ", value );
}

Upvotes: 53

Related Questions