27

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?

1

3 Answers 3

53

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 );
}
Sign up to request clarification or add additional context in comments.

Comments

6

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;
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.